'Dynamic Icons in Flutter
I retrieve some data from my DB, where I have a Column called "icon" in which I stored some Strings. For each of them, I want to pass in the Icon class of Flutter, charging the corresponding Icon. I have the single String inside
items[index]["icon"]
But I can't pass it inside Icon(items[index]["icon"])
How can I do?
Solution 1:[1]
You can use the icons directly with their literal names by accessing the Material Icons font directly with Text()
widget.
Example:
Text(
'perm_contact_calendar',
style: TextStyle(fontFamily: 'MaterialIcons'),
);
You may use it for custom Icon class to integrate with Material Framework smoothly, but in this case you will need a --no-tree-shake-icons
flag for build command since non-constant IconData constructor breaks icon tree shaking.
Solution 2:[2]
This might help someone in the future.
You do not need to use any Map to create an icon from dynamic name (too much copy-pasting). Instead of icon names you can use icon's numeric identifier from the Icons Class.
Example:
int iconCode = 58840;
// Will display "Up arrow" icon from the list
Icon(IconData(iconCode, fontFamily: 'MaterialIcons'));
Solution 3:[3]
You need a mapping from string to your icon either Icons or FontAwesomeIcons or ...
Map<String, IconData> iconMapping = {
'facebook' : FontAwesomeIcons.facebook,
'twitter' : FontAwesomeIcons.twitter,
'home' : FontAwesomeIcons.home,
'audiotrack' : Icons.audiotrack,
};
@override
Widget build(BuildContext context) {
return Icon(iconMapping [icon], color: HexColor(color));
}
similar question and answer
Trying to dynamically set the Icon based on a JSON string value
Flutter: Show different icons based on value
Solution 4:[4]
Try this out. this is exact thing you are looking for.
Widget buildRemoteIcon(){
// var remoteIconData = new RemoteIconData(Icons.add); // -> flutter native material icons
// var remoteIconData = new RemoteIconData("material://Icons.add"); // -> native material icons remotely (dynamically)
// var remoteIconData = new RemoteIconData("https://example.com/svg.svg"); // -> loading remote svg
// var remoteIconData = new RemoteIconData("assets/icons/add.png"); // -> loading local assets
// var remoteIconData = new RemoteIconData("custom-namespace://CustomIcons.icon_name"); // -> (requires pre-usage definition)
var remoteIconData = new RemoteIconData();
return RemoteIcon(icon: remoteIconData, color: Colors.black);
}
https://github.com/bridgedxyz/dynamic/tree/master/flutter-packages/x_icon
Solution 5:[5]
Use This Package From here you can get Material Icons + FontAwesome Icons also you just need to pass the icon name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Thepeanut |
Solution 3 | chunhunghan |
Solution 4 | |
Solution 5 | Sakibul Haque |