Objective : I want to have different timing duration for each color
Blue = 2 seconds
Red = 5 seconds
Green = 1 seconds
Yellow = 8 seconds
I got the code from here How to render child without parent when using setState?,
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: Sample()));
}
class Sample extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("Parent Widget rebuild");
return SafeArea(
child: Column(
children: [
Container(
height: 50,
width: 50,
color: Colors.red,
),
SizedBox(height: 20),
ChangingColor(),
],
),
);
}
}
class ChangingColor extends StatefulWidget {
@override
_ChangingColorState createState() => _ChangingColorState();
}
class _ChangingColorState extends State<ChangingColor> {
Timer _timer;
Color _color;
List<Color> arrColors = [Colors.blue, Colors.red, Colors.green, Colors.yellow] ;
int _pos =0;
List<int> arrSeconds = [2,5,1,8]; //here I set array for seconds
@override
void initState() {
for (var e in arrSeconds) {
_timer = Timer.periodic(Duration(seconds: e), (Timer t) { //I want the array looping using different seconds
print("seconds: $e");
setState(() {
_pos = (_pos + 1) % arrColors.length;
});
});}
super.initState();
}
@override
Widget build(BuildContext context) {
print("Child Widget rebuild");
return Container(
height: 50,
width: 50,
color: arrColors[_pos],
);
}
@override
void dispose() {
_timer.cancel();
_timer = null;
super.dispose();
}
}
The problem is seems like the timer did not finish yet but the color keep changing. Should I use async?