在我的应用中使用font_awesome_flutter来显示一些图标。
am从json中获取字符串形式的图标名称..我如何将其传递给图标?
有没有办法做到这一点?
例如:
我从json中获取
String icon = 'ad';
然后我要像这样使用它:
new Icon(FontAwesomeIcons.icon),
我知道它不能像这样工作..但是我该怎么做?这可行吗?
答案 0 :(得分:0)
我发现一种可以帮助您的方法。如下编辑 font_awesome_flutter.dart 文件,并按以下方式访问。
我只演示了两个Icon,您可以根据需要或全部进行下去。
font_awesome_flutter.dart
库font_awesome_flutter;
import 'package:flutter/widgets.dart';
import 'package:font_awesome_flutter/icon_data.dart';
// THIS FILE IS AUTOMATICALLY GENERATED!
class FontAwesomeIcons {
static const createDoc = {
'fiveHundredPx': IconDataBrands(0xf26e),
'accessibleIcon': IconDataBrands(0xf368),
//.......add all Icons HERE
};
static const IconData fiveHundredPx = const IconDataBrands(0xf26e);
static const IconData accessibleIcon = const IconDataBrands(0xf368);
static const IconData accusoft = const IconDataBrands(0xf369);
static const IconData acquisitionsIncorporated = const IconDataBrands(0xf6af);
static const IconData ad = const IconDataSolid(0xf641);
static const IconData addressBook = const IconDataRegular(0xf2b9);
static const IconData solidAddressBook = const IconDataSolid(0xf2b9);
static const IconData addressCard = const IconDataRegular(0xf2bb);
static const IconData solidAddressCard = const IconDataSolid(0xf2bb);
//.......
//.......add all Icons HERE To as already in your file
}
现在您可以将其用作以下代码:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() {
runApp(new FontAwesomeGalleryApp());
}
class FontAwesomeGalleryApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Font Awesome Flutter Gallery',
theme: new ThemeData.light().copyWith(
iconTheme: new IconThemeData(size: 36.0, color: Colors.black87),
textTheme: new TextTheme(
body1: new TextStyle(fontSize: 16.0, color: Colors.black87),
),
),
home: new Home(),
);
}
}
class Home extends StatelessWidget {
String data = 'fiveHundredPx';
@override
Widget build(BuildContext context) {
return Scaffold(
body: new Container(
child: Center(
child: Icon(FontAwesomeIcons.createDoc[data.toString()]),
),
),
);
}
}
我知道“这种方式”有点难,但我只是发现这种方式。
答案 1 :(得分:0)
您可以将unicode数据保存在Json中。例如:
static const IconData clock = const IconDataRegular(0xf017);
将f017保存在Json中。
以后使用以下函数转换为int。
int getHexFromStr(String fontCode) {
int val = 0;
int len = fontCode.length;
for (int i = 0; i < len; i++) {
int hexDigit = fontCode.codeUnitAt(i);
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 65 && hexDigit <= 70) {
// A..F
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 97 && hexDigit <= 102) {
// a..f
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
} else {
throw new FormatException("An error occurred when converting");
}
}
return val;
}
最后使用以下命令:
Icon(IconDataSolid(getHexFromStr(' f017')))