Flutter:在小部件调用中使用参数(图标)
Flutter: Use a parameter inside a widget call (Icon)
我是 Flutter 新手。我提取了一个小部件以创建登录按钮。
我想传递一个指定应该使用的图标的参数,但是我不能在图标小部件的方法调用中添加我的参数。如何管理?
图标小部件内出现错误。
代码:
class LoginButtonIcon extends StatelessWidget {
final String iconName;
const LoginButtonIcon({Key key, @required this.iconName}) : super(key: key);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () => "Pressed",
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(
Icons.iconName,
color: Colors.white,
),
SizedBox(
width: 15,
),
Text("RaisedButton",
style: TextStyle(color: Colors.white, fontSize: 14)),
],
),
color: Colors.black54);
}
}
iconName 类型不应该是 String, 它应该是 IconData 你应该像这样传递完整的图标 Icons.add
你走对了。现在声明一个 return 和 Icon-Widget 的函数。在函数中使用 switch-case,到 return 不同的图标,具体取决于作为参数传递的字符串。
Icon _getCorrectIcon() {
switch (iconName) {
case 'name-a':
return Icon(Icons.a);
case 'name-b':
return Icon(Icons.b);
case 'name-c':
return Icon(Icons.c);
default:
return Icon(Icons.a);
}
}
将您的行替换为:
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
_getCorrectIcon(),
SizedBox(
width: 15,
),
Text("RaisedButton",
style: TextStyle(color: Colors.white, fontSize: 14)),
],
),
我是 Flutter 新手。我提取了一个小部件以创建登录按钮。 我想传递一个指定应该使用的图标的参数,但是我不能在图标小部件的方法调用中添加我的参数。如何管理?
图标小部件内出现错误。 代码:
class LoginButtonIcon extends StatelessWidget {
final String iconName;
const LoginButtonIcon({Key key, @required this.iconName}) : super(key: key);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () => "Pressed",
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(
Icons.iconName,
color: Colors.white,
),
SizedBox(
width: 15,
),
Text("RaisedButton",
style: TextStyle(color: Colors.white, fontSize: 14)),
],
),
color: Colors.black54);
}
}
iconName 类型不应该是 String, 它应该是 IconData 你应该像这样传递完整的图标 Icons.add
你走对了。现在声明一个 return 和 Icon-Widget 的函数。在函数中使用 switch-case,到 return 不同的图标,具体取决于作为参数传递的字符串。
Icon _getCorrectIcon() {
switch (iconName) {
case 'name-a':
return Icon(Icons.a);
case 'name-b':
return Icon(Icons.b);
case 'name-c':
return Icon(Icons.c);
default:
return Icon(Icons.a);
}
}
将您的行替换为:
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
_getCorrectIcon(),
SizedBox(
width: 15,
),
Text("RaisedButton",
style: TextStyle(color: Colors.white, fontSize: 14)),
],
),