How to pass String type parameter in function to IconData in Flutter
Solution 1
https://api.flutter.dev/flutter/material/Icons-class.html
On the document linked above, we can use the codePoint field.
IconData(60969, fontFamily: 'MaterialIcons')
60969 is codePoint for the material icon named "ac unit outlined".
iconDataCodePoint: Icons.ac_unit_outlined.codePoint
Example usage:
Icon(
events.iconDataCodePoint != null
? IconData((events.iconDataCodePoint as int),
fontFamily: 'MaterialIcons')
: Icons.announcement_rounded,
size: 30,
),
Solution 2
Flutter's Icons class gets its icons from MaterialFonts like this:
IconData icon = IconData(0xea00, fontFamily: 'MaterialIcons')
That hex number is the Unicode codepoint for the glyph in the font.
You could use a Map<String,Int> to map your json icon String value to the codepoint int you want it to represent. For example:
Map<String, Int> iconCodepoint = {
'credit_card': 0xe06c,
'gift_card' : 0xe020,
//etc.
}
//String iconName holds your icon String value ('credit_card')
studentFeeButtonMenu(context, 'Hello World', IconData(iconCodepoint[iconName], fontFamily: 'MaterialIcons');
The .codepoint files here contain the glyph codepoint numbers: Material-Design-icons on Github
![Amir](https://i.stack.imgur.com/ZjUue.jpg?s=256&g=1)
Amir
Updated on December 25, 2022Comments
-
Amir over 1 year
I've been working with this flutter project for 2 weeks, and I've a problem in how to pass String type parameter in function to IconData type. Before that, I've JSON response like this:
{ "status": "success", "data": { "general": [ { "id": 1, "name": "Sumbangan Pembinaan Pendidikan", "icon": "credit_card", "type": "monthly", "amount": 125000 }, { "id": 2, "name": "Uang Bangunan", "icon": "credit_card", "type": "yearly", "amount": 1250000 } ],
I want to pass 'icon' key, and my button function look like this:
Widget studentFeeButtonMenu(BuildContext context, String text, IconData iconFee){ return Container( width: double.infinity, height: screenHeight(context)*(1/12), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), ), child: Center( child: Container( width: screenWidth(context)*(1/1.3), height: double.infinity, color: Colors.red, child: Row( children: [ Icon( iconFee, color: Color(0xff84923f), ), SizedBox( width: screenWidth(context)*(1/10), ), Text( text, style: TextStyle( color: Colors.black, ), ), ], ), ), ), ); }
I want to create ListView.builder and the itemBuilder is using that function, like this:
child: ListView.builder( itemCount: generalStudentFees == null ? 0 : generalStudentFees.length, itemBuilder: (context, index){ return studentFeeButtonMenu(context, generalStudentFees[index]['name'], Icons.generalStudentFees[index]['icon']); }, ),
The 'name' key is working perfectly and can fetch with the data, but I don't know how to pass the icon, the error message says:
The getter 'generalStudentFees' isn't defined for the type 'Icons'.