skip to Main Content

The icon to use is a name received from server side, e.g., "lock",

How to map "lock" to Icons.lock?

 Icon(Icons.lock)

Do I need to create a Map from string(name) to flutter icon constants? Expecting a static method

 Icons.fromName(String name)

4

Answers


  1. here is an example of how you can do 🙂

    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Material App',
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Material App Bar'),
            ),
            body: Center(
              child: Icon(IconMapper.fromName('lock')),
            ),
          ),
        );
      }
    }
    
    class IconMapper {
      static final _iconMap = <String, IconData>{
        'lock': Icons.lock,
        'alarm': Icons.alarm,
        'call': Icons.call,
        'camera_alt': Icons.camera_alt,
        // Add more icons as needed
      };
    
      static IconData fromName(String name) {
        return _iconMap[name] ??
            Icons.error; // Fallback to 'error' icon if name not found
      }
    }
    
    Login or Signup to reply.
  2. No need to maintain map, what you can do is,

    Instead of

    Icon(Icons.lock)
    

    use

    Icon(IconData(0xe3ae, fontFamily: 'MaterialIcons'))
    

    Where 0xe3ae needs to be passed from server, and it is int.

    You can find code for each icon on flutter/src/materials/icons.dart .
    You can navigate to that file by tapping on Icon.icon_name on your code.

    Login or Signup to reply.
  3. import 'package:flutter/material.dart';
    
        void main() {
              String iconName = 'lock';
              IconData? iconData = IconSupport.fromName(iconName);
            
              if (iconData != null) {
                Widget iconWidget = Icon(iconData);
                print(iconWidget);
              } else {
                print('Unknown icon : $iconName');
              }
            } 
                   
            class IconSupport {
              static IconData? fromName(String name) {
                 if (name == 'lock') {
                    return Icons.lock;
               } else {
              return null; 
            }
          }
        }
            
            
    
    Login or Signup to reply.
  4. You can use the simple switch-case method:

    Icon displayIcon (nameOrIndex){
       switch (nameOrIndex) {
          case "lock":
             return Icon(Icons.lock);
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search