How to Create Random Color Generator Background In Flutter

How to Create Random Color Generator Background In Flutter??

Earlier we have been through articles like Add Query Parameters to DART HTTP Request. So in this article, we will go through how to Create Random Color Generator Background In Flutter.

Are you ready for the same? So let’s dive into the same.

How to Create Random Color Generator Background In Flutter??

You can use Random class to do that:

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

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

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

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

class _MyAppState extends State {
  List colors = [Colors.red, Colors.green, Colors.yellow];
  Random random = new Random();

  int index = 0;

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () => changeIndex(),
        child: Text('Click'),
        style: ElevatedButton.styleFrom(
          backgroundColor: colors[index],
        ),
      ),
    );
  }
}

Also, there is a package called random_pk by Pawan Kumar, that will give us random color each and every time your app’s build method gets called.

So this how to get a random color:

Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)

There is an in-built list of material colors in the Colors class. You can use it like below

Colors.primaries[Random().nextInt(Colors.primaries.length)]

So we can use this for e.g

import 'dart:math';

Icon(
    Icons.account_circle,
    size: 40,
    color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
)
import 'dart:math';
import 'dart:ui';

class Util {
  static Color randomColor() {
    return Color(Random().nextInt(0xffffffff));
  }
}

For Opaque Color:

static Color randomOpaqueColor() {
  return Color(Random().nextInt(0xffffffff)).withAlpha(0xff);
}

So this will generate a different color for the button every time the build method for the app is called.

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
        title: "Elevated Button",
        theme: new ThemeData(
          primarySwatch: Colors.teal,
        ),
        home: new HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State {
  //contains the colours for the circle Avatars
  final List circleColors = [Colors.red, Colors.blue, Colors.green];
  int currentIndex = 0; // Track the current button color index

  Color randomGenerator() {
    currentIndex = new Random().nextInt(3); // Update currentIndex within the function
    return circleColors[currentIndex];
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () => setState(() => randomGenerator()), // Update state inside onPressed
        child: Text('Click'),
        style: ElevatedButton.styleFrom(
          backgroundColor: randomGenerator(), // Call randomGenerator to get the color
        ),
      ),
    );
  }
}

Another way to get tons of colors is by using Random class with Color.fromARGB or Color.fromRGBO:

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

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

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => new _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final Random _random = Random();

  Color _color = Color(0xFFFFFFFF);

  void changeColor() {
    setState(() {
      _color = Color.fromARGB(
        //or with fromRGBO with fourth arg as _random.nextDouble(),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: InkWell(
        onTap: changeColor,
        child: Container(
          color: _color,
        ),
      ),
    );
  }
}

If you use Color.fromRGBO:

The fourth argument should be within 0.0 to 1.0 and fortunately, we have _random.nextDouble() that gives a value between 0.0 to 1.0 randomly.

By the way:

  • R – Red
  • B – Blue
  • G – Green
  • O – Opacity
  • A – Alpha

To get the random color I do the next:

import 'dart:math' as math;

final rnd = math.Random();

Color getRandomColor() => Color(rnd.nextInt(0xffffffff));

We can use random class for that But there is a random_color plugin in the flutter that can help us for generating random color and also we can select high saturation colors with this code:

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorSaturation: ColorSaturation.highSaturation
);

And light colors with this code:

import 'package:random_color/random_color.dart';

RandomColor _randomColor = RandomColor();

Color _color = _randomColor.randomColor(
  colorBrightness: ColorBrightness.light
);

Conclusion:

So in this article, We have been through How to Create Random Color Generator Background In Flutter.

Keep Learning !!! Keep Fluttering !!!

So if you are still confused about something in Flutter Development!! Lets us know, we would love to assist you.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields