颤振 - 使用 for 循环或列表创建具有可编辑属性的自定义小部件



我创建了一个自定义类RectButton,具有buttonChild,bgColor和onPress的可编辑属性。我希望通过创建一个新的小部件来使这个小部件进一步动态化,该小部件可以根据可变整数(即一个屏幕上的 4 个按钮,另一个屏幕上的 3 个按钮等(创建一行这些 RectButtons,但无法弄清楚如何继续具有完全可编辑的属性(bgColor 不依赖于索引,即 bgColor: 颜色.红色[100 + 100 * 索引](在新小部件中。

class RectButton extends StatelessWidget {
RectButton({this.buttonChild, this.bgColor, this.onPress});
final Widget buttonChild;
final Color bgColor;
final Function onPress;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
constraints: BoxConstraints.expand(width: 100, height: 50),
child: Center(child: buttonChild),
decoration: BoxDecoration(
color: bgColor,
shape: BoxShape.rectangle,
border: Border.all(width: 1, color: Colors.white)),
padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
),
);
}
}

有什么想法吗?任何帮助都非常感谢。我一直在谷歌上搜索我能找到的所有循环和列表,但没有运气。此外,任何资源也受到赞赏 - 有点新来颤动:)

编辑:更新的代码

import 'package:flutter/material.dart';
import 'rect_button.dart';
enum Options { option0, option1, option2, option3 }
class Screen1 extends StatefulWidget {
@override
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
List<Widget> makeButtons(int num, List<Widget> children, List<Color> colors,
List<Function> onPresses) {
List<Widget> buttons = new List();
for (int i = 0; i < num; i++) {
buttons.add(RectButton(children[i], colors[i], onPresses[i]));
}
return buttons;
}
Options selectedOption;
@override
Widget build(BuildContext context) {
int num = 2;
List<Widget> children = [
Text("A"),
Text("B"),
];
List<Color> colors = [
selectedOption == Options.option0 ? Colors.red : Colors.green,
selectedOption == Options.option1 ? Colors.red : Colors.green
];
List<Function> onPresses = [
() {
setState(() {
selectedOption = Options.option0;
});
},
() {
setState(() {
selectedOption = Options.option1;
});
},
];
// 3rd method does nothing
return Scaffold(
appBar: AppBar(
title: Text('title'),
),
body: Row(
children: makeButtons(3, children, colors, onPresses),
),
);
}
}

如果可以为每个孩子、颜色、onPress 创建列表,则可以使用以下代码循环并创建RectButton列表:

List<Widget> makeButtons(int num, List<Widget> children, List<Color> colors, List<Function> onPresses){
List<Widget> buttons = new List();
for(int i = 0; i < num; i ++){
buttons.add(RectButton(buttonChild: children[i], bgColor: colors[i], onPress: onPresses[i]));
}
return buttons;
}

您可以将其与以下Row一起使用:

Row(
children: makeButtons(...),
),

您还可以修改makeButtons方法以添加可选参数,以防您想要一种颜色一致/具有 [100+100*i] 差异等。

编辑:使用构建方法的示例:

Widget build(BuildContext context) {
int num = 2;
List<Widget> children = [Text("A"), Text("B"), Text(_counter.toString())];
List<Color> colors = [Colors.red, Colors.blue, Colors.green];
List<Function> onPresses = [_incrementCounter, _decrementCounter, (){}];
// 3rd method does nothing
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Row(
children: makeButtons(3, children, colors, onPresses),
),
);
}

最新更新