[英]How to pass Navigator or Void function as a parameter to a ListTile Widget -Flutter
我正在從我的主頁調用小部件,並將所需的數據作為參數發送。 像這樣:
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 還是其他?
您只需在小部件中創建一個類型並將其用作構造函數參數。
例如:
//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
);
}
}
使用 VoidCallback 代替函數
final VoidCallback action;
只需在AppDrawerListTile
類中的action
上添加( )
,代碼應該是
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.