zzomtceo
zzomtceo

Reputation: 47

How to change background color on time with Flutterr?

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

Answers (1)

Blasanka
Blasanka

Reputation: 22447

Here are the basic steps:

  1. Override the setState() inside MainAppState or according to your needs you can override initState().
  2. Inside it add a Timer.periodic
  3. assign a value to 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

Related Questions