Reputation: 47
I have been completely unable to figure this out. After a good deal of research and screwing around I can't see a way to link a Timer.periodic
to the setState
of the state of a stateful widget. I'm trying to change the background color of my app each frame (or just every 17ms, close enough) to have a gradual change, by incrementing through an array of color values that I've defined. I just don't know how to do the actual changing based on the timer and I'm totally lost at this point.
Edit: Here is the full code of the app so far.
import 'package:flutter/material.dart';
import 'colors.dart';
import 'dart:math';
import 'dart:async';
final Random randProgress = new Random();
final rgb_color_container rgbColorContainer = new rgb_color_container();
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MainApp();
}
}
class MainApp extends StatefulWidget {
@override
MainAppState createState() => new MainAppState();
}
class MainAppState extends State<MainApp> {
int colorSpeed = 1;
int colorProgress = randProgress.nextInt(1530);
@override
Widget build(BuildContext context){
return new MaterialApp(
home: new Scaffold(
),
theme: ThemeData(
canvasColor: rgbColorContainer.light[colorProgress],
primaryColor: rgbColorContainer.dark[colorProgress],
accentColor: rgbColorContainer.dark[colorProgress],
),
);
}
}
Upvotes: 3
Views: 2588
Reputation: 22447
Here are the basic steps:
setState()
inside MainAppState
or according to your needs you can override initState()
.Timer.periodic
colorProgress
by changing colorProgress
with
timer.Like below(not checked, only the idea):
Timer timer;
@override
void initState() {
super.initState();
timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) {
setState(() {
//change your colorProgress here
});
});
}
@override
void dispose() {
super.dispose();
timer.cancel();
}
These may help:
How to create Timer.periodic
.
Change color.
setState not update.
Upvotes: 4