[英]How to pass String type parameter in function to IconData in Flutter
我已经使用这个颤振项目 2 周了,我在如何将函数中的 String 类型参数传递给 IconData 类型时遇到了问题。 在此之前,我有这样的 JSON 响应:
{
"status": "success",
"data": {
"general": [
{
"id": 1,
"name": "Sumbangan Pembinaan Pendidikan",
"icon": "credit_card",
"type": "monthly",
"amount": 125000
},
{
"id": 2,
"name": "Uang Bangunan",
"icon": "credit_card",
"type": "yearly",
"amount": 1250000
}
],
我想传递“图标”键,我的按钮功能如下所示:
Widget studentFeeButtonMenu(BuildContext context, String text, IconData iconFee){
return Container(
width: double.infinity,
height: screenHeight(context)*(1/12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Container(
width: screenWidth(context)*(1/1.3),
height: double.infinity,
color: Colors.red,
child: Row(
children: [
Icon(
iconFee,
color: Color(0xff84923f),
),
SizedBox(
width: screenWidth(context)*(1/10),
),
Text(
text,
style: TextStyle(
color: Colors.black,
),
),
],
),
),
),
);
}
我想创建 ListView.builder 并且 itemBuilder 正在使用该函数,如下所示:
child: ListView.builder(
itemCount: generalStudentFees == null ? 0 : generalStudentFees.length,
itemBuilder: (context, index){
return studentFeeButtonMenu(context, generalStudentFees[index]['name'], Icons.generalStudentFees[index]['icon']);
},
),
'name' 键工作正常,可以获取数据,但我不知道如何传递图标,错误消息说:
getter 'generalStudentFees' 没有为类型 'Icons' 定义。
Flutter 的 Icons 类从 MaterialFonts 中获取图标,如下所示:
IconData icon = IconData(0xea00, fontFamily: 'MaterialIcons')
该十六进制数字是字体中字形的 Unicode 代码点。
您可以使用 Map<String,Int> 将您的 json 图标 String 值映射到您希望它表示的代码点 int。 例如:
Map<String, Int> iconCodepoint = {
'credit_card': 0xe06c,
'gift_card' : 0xe020,
//etc.
}
//String iconName holds your icon String value ('credit_card')
studentFeeButtonMenu(context, 'Hello World', IconData(iconCodepoint[iconName], fontFamily: 'MaterialIcons');
此处的 .codepoint 文件包含字形代码点编号: Github 上的 Material-Design-icons
https://api.flutter.dev/flutter/material/Icons-class.html
在上面链接的文档中,我们可以使用 codePoint 字段。
IconData(60969, fontFamily: 'MaterialIcons')
60969 是名为“ac unit outlines”的材质图标的代码点。
iconDataCodePoint: Icons.ac_unit_outlined.codePoint
用法示例:
Icon(
events.iconDataCodePoint != null
? IconData((events.iconDataCodePoint as int),
fontFamily: 'MaterialIcons')
: Icons.announcement_rounded,
size: 30,
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.