我已经使用fluttericon.com创建了自定义字体图标,如下所示:
// fa_pro_light_icons.dart
import 'package:flutter/widgets.dart';
class FaProLight {
FaProLight._();
static const _kFontFam = 'FaProLight';
static const IconData cash_register = const IconData(0xe800, fontFamily: _kFontFam);
static const IconData chart_pie = const IconData(0xe801, fontFamily: _kFontFam);
}
然后我从服务器以字符串形式获取图标名称
// dummy_data.dart
const SAY_SOME_DUMMY_DATA = const [
MyModel(id: '1', icon: 'cash_register'),
MyModel(id: '1', icon: 'chart_pie'),
];
我的模型如下:
class MyModel {
final String id;
final String icon;
const MyModel({ this.id, this.icon });
}
我的列表生成器如下:
Widget _listItemBuilder(BuildContext context, int index) {
const items = SAY_SOME_DUMMY_DATA;
return ListItem(
avatar: CircleAvatar(
child: Icon(FaProLight.cash_register) // this work - no problem
child: Icon(FaProLight.[items[index].icon]) // But, How to make this work?
),
);
}
所以我的问题是:
如上所述如何使这项工作FaProLight.[items[index].icon]
?
答案 0 :(得分:2)
您无法使用Dart中的字符串访问成员,但是,您可以简单地将成员转换为地图:
class FaProLight {
FaProLight._();
static const _kFontFam = 'FaProLight';
static const Map<String, IconData> icons = {
'cash_register': IconData(0xe800, fontFamily: _kFontFam),
'chart_pie': IconData(0xe801, fontFamily: _kFontFam),
};
}
现在,您可以通过以下方式访问它:
CircleAvatar(
child: Icon(FaProLight.icons[items[index].icon]),
)