gpt4 book ai didi

flutter - Flutter将点击操作添加到列表并使用它们

转载 作者:行者123 更新时间:2023-12-03 04:51:02 24 4
gpt4 key购买 nike

在我的应用程序中,我想创建一个自定义 Action 列表,例如Drawer中的菜单,我创建了这个简单的 Action 列表和菜单项

List listOfMaps=[];
@override
void initState() {
super.initState();
listOfMaps.add({'name':'menu 1','action':_dashboardClick()});
listOfMaps.add({'name':'menu 2','action':_aboutUsClick()});
}

用作 Action :
Function _dashboardClick(){
print('you clicked on _dashboardClick button');
return null;
}

Function _aboutUsClick(){
print('you clicked on _aboutUsClick button');
return null;
}

我尝试在 Column中显示它们:
Expanded(
child: Column(
children: <Widget>[
...listOfMaps.map( (item) =>
ListTile(
title: Text("${item['name']}"),
onTap:()=> item['action'],
) )
],
),
),

现在,我可以将菜单项放入 ListTile,但操作不起作用

最佳答案

问题是,在添加列表时,您正在调用方法,即使在构建小部件时,您也可以在日志中看到打印消息。并且您没有调用onTap方法,则必须在其后添加()

以下代码可为您提供更多帮助。

 List listOfMaps = [];
@override
void initState() {
super.initState();
listOfMaps.add({'name': 'menu 1', 'action': _dashboardClick}); // () removed
listOfMaps.add({'name': 'menu 2', 'action': _aboutUsClick}); // () removed
}

Function _dashboardClick() {
print('you clicked on _dashboardClick button');
return null;
}

Function _aboutUsClick() {
print('you clicked on _aboutUsClick button');
return null;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
drawer: Drawer(
child: Column(
children: <Widget>[
...listOfMaps.map((item) => ListTile(
title: Text("${item['name']}"),
onTap: () => item['action'](), // () added
))
],
),
),
);
}

关于flutter - Flutter将点击操作添加到列表并使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61336572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com