For some reason the widgets are not behaving as expected when the floating action button is clicked:
class _MyHomePageState extends State<MyHomePage> {
List<Widget> widgets = [
Container(
key: UniqueKey(),
color: Colors.redAccent,
child: Text("0", style: TextStyle(fontSize: 40)),
),
Container(
key: UniqueKey(),
color: Colors.blueAccent,
child: Text("1", style: TextStyle(fontSize: 40)),
),
Container(
key: UniqueKey(),
color: Colors.greenAccent,
child: Text("2", style: TextStyle(fontSize: 40)),
),
];
List<int> homePageWidgetSequence = [0, 1, 2];
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
for (int i = 0; i < 3; i++)
if (homePageWidgetSequence[i] == 0) widgets[i],
for (int i = 0; i < 3; i++)
if (homePageWidgetSequence[i] == 1) widgets[i],
for (int i = 0; i < 3; i++)
if (homePageWidgetSequence[i] == 2) widgets[i],
Text((count-1).toString(), style: TextStyle(fontSize: 40))
]),
floatingActionButton: FloatingActionButton(onPressed: () {
setState(() {
if (count == 0) {
homePageWidgetSequence = [1, 0, 2];
} else if (count == 1) {
homePageWidgetSequence = [2, 0, 1];
} else if (count == 2) {
homePageWidgetSequence = [2, 1, 0];
}
print(count);
count++;
});
}),
);
}
}
The widgets are suppose to be displaying sequence 2,0,1 but it displays 1,2,0 instead. It worked when count equals 0 and 2.
Screenshot
I was suspecting some sort of key issue when building but it doesn’t fix it after adding UniqueKey(), could someone help me with it? Thank you!