I created a custom class, RectButton, with editable properties of buttonChild, bgColor, and onPress. I was hoping to make this widget further dynamic by creating a new widget that can create a row of these RectButtons based on a variable integer (i.e. 4 buttons on one screen, 3 on another screen, etc) but cant figure out how to continue to have completely editable properties (bgColor isn't depended on index, i.e. bgColor: Colors.red[100 + 100 * index]) in the new widget.
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),
),
);
}
}
Any thoughts? Any help is much appreciated. Ive been googling everything I can find about for loops and lists with no luck. Also any resources are also appreciated-- kinda new to flutter :)
Edit: Updated Code
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),
),
);
}
}