Cyril Ferté
Cyril Ferté

Reputation: 21

Flutter call dynamicaly function attribute with string

Want to call Icons.album with the string "album" like Icons["album"] but it's not work's. do I need to do enum for each icon or it was a other way ?

List tasks = [{
    "title": "task 1",
    "description": "description 1",
    "icon": "ring_volume",
  },{
    "title": "task 2",
    "description": "description 2",
    "icon": "flag",
  },{
    "title": "task 3",
    "description": "description 3",
    "icon": "album",
  },
  ];

[...]

  Widget taskCard(Map task) {
    Text title = Text(task['title']);
    return Center(
      child: Card(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
             ListTile(
              leading: Icons(Icons.album), // HERE
              title: new Text(task['title']),
              subtitle: new Text(task['description']),
            ),

          ],
        ),
      ),
    );

  }

Upvotes: 2

Views: 61

Answers (2)

Wehid Behrami
Wehid Behrami

Reputation: 266

you should use this:

in dictionary:

"icon": Icons.album

and in widget:

leading: Icon(task["icon"])

Upvotes: 0

JideGuru
JideGuru

Reputation: 7670

You cannot call the icons like these Icons["album"] but you can store IconData in the maps like this

List tasks = [{
    "title": "task 1",
    "description": "description 1",
    "icon": Icons.ring_volume,
  },{
    "title": "task 2",
    "description": "description 2",
    "icon": Icons.flag,
  },{
    "title": "task 3",
    "description": "description 3",
    "icon": Icons.album,
  },
  ];

then call it in your UI the like task['icon']

  Widget taskCard(Map task) {
    Text title = Text(task['title']);
    return Center(
      child: Card(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
             ListTile(
              leading: Icons(task['icon']), // HERE
              title: new Text(task['title']),
              subtitle: new Text(task['description']),
            ),

          ],
        ),
      ),
    );

  }

Upvotes: 1

Related Questions