DolDurma
DolDurma

Reputation: 17289

Flutter add click actions to list and using them

in my application i want to make custom list of actions such menus in Drawer, i created this simple list of actions and menu itmes

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

functions as actions:

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

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

and i try to show them inside Column:

Expanded(
  child: Column(
    children: <Widget>[
      ...listOfMaps.map( (item) =>
          ListTile(
            title: Text("${item['name']}"),
            onTap:()=> item['action'],
          ) )
    ],
  ),
),

now, in that i can put menu items into ListTile, but actions doesn't work

Upvotes: 0

Views: 2021

Answers (1)

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

The problem is that while adding in list you are calling method so, even while building widget you can see print message in log. and you are not calling method onTap, you have to add () behind that.

Following code help you more.

 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
                ))
          ],
        ),
      ),
    );
  }

Upvotes: 1

Related Questions