我正在從我的主頁呼叫小部件,并將所需的資料作為引數發送。像這樣:
AppDrawerListTile(
title: 'Logout', // title of the List Tile.
icon: Icons.logout, // icon for the list tile.
action: () { // onTap action for ListTile - which is not working
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()));
}),
這是自定義公共串列,我在其中獲取引數并將其提供給 ListTile。
class AppDrawerListTile extends StatelessWidget {
final String title;
final IconData icon;
final Function action;
const AppDrawerListTile({
Key? key,
required this.title,
required this.icon,
required this.action,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
minVerticalPadding: 0,
title: title.text.make().p0(),
dense: true,
// visualDensity: const VisualDensity(horizontal: -2, vertical: -3),
// leading: Image(image: AssetImage('assets/images/mmsc_logo.png')),
leading: Icon(icon),
minLeadingWidth: 5,
onTap: () => action, // Here I want the passed navigator function to work.
);
}
}
除了 onTap 操作方法外,一切都在這里作業,我不明白,我應該將變數宣告為 Function 還是其他?
uj5u.com熱心網友回復:
您只需在小部件中創建一個型別并將其用作建構式引數。
例如:
//here declare the type
typedef TypeNameYouWant = void Function();
class AppDrawerListTile extends StatelessWidget {
final String title;
final IconData icon;
final TypeNameYouWant action; //here use the type declared
const AppDrawerListTile({
Key? key,
required this.title,
required this.icon,
required this.action,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
minVerticalPadding: 0,
title: title.text.make().p0(),
dense: true,
// visualDensity: const VisualDensity(horizontal: -2, vertical: -3),
// leading: Image(image: AssetImage('assets/images/mmsc_logo.png')),
leading: Icon(icon),
minLeadingWidth: 5,
onTap: () => action(), // Here you use your action param like a fn
);
}
}
uj5u.com熱心網友回復:
使用 VoidCallback 代替函式
final VoidCallback action;
uj5u.com熱心網友回復:
只需在課堂( )上添加,代碼應該是actionAppDrawerListTile
onTap: () => action(),
完整代碼
class AppDrawerListTile extends StatelessWidget {
final String title;
final IconData icon;
final Function action;
const AppDrawerListTile({
Key? key,
required this.title,
required this.icon,
required this.action,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
minVerticalPadding: 0,
title: title.text.make().p0(),
dense: true,
// visualDensity: const VisualDensity(horizontal: -2, vertical: -3),
// leading: Image(image: AssetImage('assets/images/mmsc_logo.png')),
leading: Icon(icon),
minLeadingWidth: 5,
onTap: () => action(), // Here I want the passed navigator function to work.
);
}
}
為什么?
如果沒有()標志,則表示onTap呼叫匿名函式,該函式回傳action并且不呼叫action.
() => action // returns action
// similar to
(){
return action;
}
如果添加()符號,則表示onTap呼叫匿名函式,匿名函式呼叫action函式。
() => action() // calls action
// similar to
(){
action();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476909.html
上一篇:使用Python截圖ADB
