尝试根据JSON字符串值动态设置图标 [英] Trying to dynamically set the Icon based on a JSON string value

查看:83
本文介绍了尝试根据JSON字符串值动态设置图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSON格式的服务器上有一个客户端配置。

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

示例JSON类似于{ icon: facebook}

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

我在下面有小部件。

    class MySocialIcons extends StatelessWidget {

    MySocialIcons({this.icon, this.color});

    final String icon;
    final String color;

    @override
    Widget build(BuildContext context) {

    switch(icon) {
      case 'facebook': {
        return Icon(FontAwesomeIcons.facebook, color: HexColor(color));
      }
      break;

      case 'twitter': {
        return Icon(FontAwesomeIcons.twitter, color: HexColor(color));
      }
      break;

      default: {
        return Icon(FontAwesomeIcons.home, color: HexColor(color));
      }
      break;
    }
  }
}

有没有办法必须为500个超酷字体写500条switch语句?格式为

Is there a way to not have to write 500 switch statements for 500 font awesome icons? the format is

FontAwesomeIcons.facebook ,其中我的字符串值 facebook将附加在FontAwesomeIcons的末尾。我正在寻找一种只在字符串中写入所需内容的方法,它会返回正确的图标小部件。

FontAwesomeIcons.facebook where my string value "facebook" would append on the end of FontAwesomeIcons. I am looking for a way to just write whatever I want in the string and it return the correct icon widget.

推荐答案

有消除某些代码重复的两种方法。

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


  1. 通过移开开关并将其移至其自己的功能中,因此您的构建方法不会重复。

切换语句

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

        case 'twitter': {
          return FontAwesomeIcons.twitter;
        }
        break;

        default: {
          return FontAwesomeIcons.home;
        }
      }
    }

构建函数

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

或2. 创建地图

Map<String, IconData> iconMapping = {
  'facebook' : FontAwesomeIcons.facebook,
  'twitter' : FontAwesomeIcons.twitter,
  'home' : FontAwesomeIcons.home
};

构建函数

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

这篇关于尝试根据JSON字符串值动态设置图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆