How to Generate Random Color in Flutter

In this example, we are going to show you the easiest way to generate infinite numbers of random colors or finite random colors from a specific list. This example is in simplified form, see the code below:

import 'dart:math';
Random random = Random();
Color tempcol = Color.fromRGBO(
    random.nextInt(255),
    random.nextInt(255),
    random.nextInt(255),
    1,
);
//tempcol is random color

import 'dart:math';
List<Color> colors = [Colors.redAccent, Colors.teal, Colors.green, Colors.grey];
Random random = Random();
int cindex = random.nextInt(colors.length);
Color tempcol = colors[cindex];
//tempcol is random color

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

void main() {
  runApp(
    MaterialApp( 
      home: MyApp()
    )
  );
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Color cone = Colors.blueAccent;
  Color ctwo = Colors.redAccent;

  //for random colors from selected list of colors
  List<Color> colors = [Colors.redAccent, Colors.teal, Colors.green, Colors.grey];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Generate Random Color"), //appbar title
              backgroundColor: Colors.redAccent //appbar background color
          ),
          backgroundColor: cone,
          body: Container(
            height: 130,
            color: ctwo,
            alignment:Alignment.topCenter,
            padding: EdgeInsets.all(15),
             child: Column(
                children:[

                  ElevatedButton(
                    onPressed:(){
                        Random random = Random();
                        Color tempcol = Color.fromRGBO(
                            random.nextInt(255),
                            random.nextInt(255),
                            random.nextInt(255),
                            1,
                        );

                        setState(() {
                            cone = tempcol;
                        });
                    }, 
                    child: Text("Random Scaffold Color")
                  ),

                  ElevatedButton(
                    onPressed:(){
                         Random random = Random();
                         int cindex = random.nextInt(colors.length);
                         Color tempcol = colors[cindex];

                         setState(() {
                            ctwo = tempcol;
                         });
                    }, 
                    child: Text("Random Container Color")
                  ),   
                ]
             )
          )
      );
  }
}

In this way, you can generate random colors in Flutter app.

No any Comments on this Article


Please Wait...