skip to Main Content

How can I convert a List<String> to List<IconData>? I have the following ['Icons.check', 'Icons.cancel'] which I get back from the database, and I need to convert it to List<IconData>.

I have tried the following:

final icons = List<String>.from(widget.values[0]['icons'] as List<IconData>

3

Answers


  1. Try saving the icon’s codePoint property to the database.

      IconData parse(int codePoint) {
        return IconData(codePoint, fontFamily: 'MaterialIcons');}
    

    Use it

    Icon(parse(0xe139)) // 0xe139 = Icons.cancel.codePoint
    
    Login or Signup to reply.
  2. Try the following code:

    List<IconData> icons = widget.values[0]['icons'].map((String element) => element == 'Icons.check' ? Icons.check : Icons.cancel).toList();
    
    Login or Signup to reply.
  3. 1. Statically

    Use Map of String and IconData like:

    Map<String, IconData> iconsMap = {
          'Icons.check': Icons.check,
          'Icons.cancel': Icons.calendar_view_day_rounded,
       };
    List<String> iconStrings = ['Icons.check', 'Icons.cancel'];
     
    List<IconData> icons = iconStrings.map((iconString) => iconsMap[iconString]!).toList();
    
    print(icons);
    

    2. Dynamically

    store the iconCode using codepoint of the Icon and you can retrieve it by parsing it.

    Example:

    IconData icon = Icons.add;
    print(icon.codePoint);  //👈 Save this in the database 
    

    Then you can get your IconData as:

    List<String> iconInts = ['0xe139', '0xe140'];
     
    List<IconData> icons = iconInts.map((iconInt) => IconData(iconInt,fontFamily:'MaterialIcons').toList();
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search