我坚持使用一个非常简单的pb:我想生成按钮而不定义列表索引。
class _MyAppState extends State<MyApp> {
final mybuttons = ['button 1', 'button 2', 'button 3']; // List defining the items
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.yellow[200], Colors.orange[300]])),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ButtonMenuList(mybuttons[0]), //button 1
ButtonMenuList(mybuttons[1]), //button 2
ButtonMenuList(mybuttons[2]), //button 3
]),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[Text(_usageRulesFr)],
),
]),
),
));
}
class ButtonMenuList extends StatelessWidget {
final buttonmen;
ButtonMenuList(this.buttonmen);
@override
Widget build(BuildContext context) {//design button
);
}
}
这有效,但并非一定要重复ButtonMenuList(),我想根据List项自动生成它们。
答案 0 :(得分:0)
您可以这样做:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.yellow[200], Colors.orange[300]])),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.center,
// Here
children: mybuttons.map((item) => ButtonMenuList(item)).toList());
//
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[Text(_usageRulesFr)],
),
]),
),
));
}
或者,您可以这样做:
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
for(var item in mybuttons) ButtonMenuList(item)
],
),