In flutter, I have widgets like:
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) => Scaffold(
body: OrientationBuilder(
builder: (context, orientation) {
const List<ColorfulBox> children = [ColorfulBox(), ColorfulBox()];
return orientation == Orientation.portrait ?
const Row(children: children) :
const Column(children: children);
},
),
);
}
class ColorfulBox extends StatefulWidget {
const ColorfulBox({super.key});
@override
State<ColorfulBox> createState() => _ColorfulBoxState();
}
class _ColorfulBoxState extends State<ColorfulBox> {
@override
Widget build(BuildContext context) => Container(
width: 100,
height: 100,
color: getRandomColor(),
);
}
Color getRandomColor() {
var generatedColor = Random().nextInt(Colors.primaries.length);
return Colors.primaries[generatedColor];
}
Currently when I rotate the device, new state of ColorfulBox
will be build what causes color change.
I was wondering how can I keep ColorfulBox
state?
I tried adding keys differently named to ColorfulBox
and also adding AutomaticKeepAliveClientMixin
but none of those two ideas worked.
2
Answers
In fact, your state of widget is not recreated, but the build function is executed again.
You need call
getRandomColor()
outside of thebuild
method:Use this code:
You could set the colors higher up, when you define the children List: