Trying to dynamically set the Icon based on a JSON string value

前端 未结 3 948
时光取名叫无心
时光取名叫无心 2021-01-15 05:47

I have a client config that is on a server in JSON format.

example JSON would be like { \"icon\" : \"facebook\" }

I have the widget below.

          


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 06:33

    There are two ways you can eliminate some of your code duplication.

    1. By taking the switch out and moving it into it's own function so your build method has no duplication in it.

    Switch statement

     IconData getIconForName(String iconName) {
          switch(iconName) {
            case 'facebook': {
            return FontAwesomeIcons.facebook;
            }
            break;
    
            case 'twitter': {
              return FontAwesomeIcons.twitter;
            }
            break;
    
            default: {
              return FontAwesomeIcons.home;
            }
          }
        }
    

    Build Function

    @override
    Widget build(BuildContext context) {
      return Icon(getIconForName(icon), color: HexColor(color));
    }
    

    or 2. Create a Map

    Map iconMapping = {
      'facebook' : FontAwesomeIcons.facebook,
      'twitter' : FontAwesomeIcons.twitter,
      'home' : FontAwesomeIcons.home
    };
    

    Build Function

    @override
    Widget build(BuildContext context) {
      return Icon(iconMapping [icon], color: HexColor(color));
    }
    

提交回复
热议问题