Flutter: How can I make a Random color generator Background


Asked by Dev E on July 14, 2018 (source).

Generate random colors

return new RaisedButton(

    padding:  EdgeInsets.symmetric(vertical: 30.0),
    color: Colors.primaries random  List <blue,green>,


Question answered by Blasanka (source).

You can use Random class to do that:

But if you want to change the color when button is pressed, you have to use a StatefulWidget. A simple example is like below:

import 'package:flutter/material.dart';
import 'dart:math';

void main() {
      home: MyApp(),

class MyApp extends StatefulWidget {
  _MyAppState createState() => _MyAppState();

class _MyAppState extends State<MyApp> {

  List colors = [Colors.red, Colors.green, Colors.yellow];
  Random random = new Random();

  int index = 0;

  void changeIndex() {
    setState(() => index = random.nextInt(3));

  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () => changeIndex(),
        child: Text('Click'),
        color: colors[index],

Also, there is a package called random_pk by pawankumar, that will give us random color each and every time your app's build method get called.