Flutter Dynamically Generate Random Background Color Dart Example

Background color is most important part for every android & iOS application. Because using background color application screen look will set. Basically in most of applications we would see single background color but sometimes app developer wants to change the background color dynamically. In today’s tutorial we would learn about Flutter Dynamically Generate Random Background Color on Button Click Dart Android iOS Example Tutorial. We are using Random class in our tutorial to generate random Integer value and put that value in Color.fromARGB() function. So let’s get started:) .

Contents in this project Flutter Dynamically Generate Random Background Color on Button Click Dart Android iOS Example Tutorial:

1. Import material.dart and math package in your app’s main.dart file.

2. Create void main runApp() method and here we would call our main MyApp view class.

3. Create our main MyApp class extend with State less widget. In this class we would call View() class in body section of Scaffold widget.

4. Create a class named as View extends with StatefulWidget. In this class we would make createState() method of state and pass ViewState() class along with it to enable mutable state management in given class tree.

5 Create a class named as ViewState extends with State. This is our main View children class.

6. Create a Color string named as colorCode with default light background color. In flutter we use Color type variable to hold all type of color strings.

7. Create a Random type of variable . We would use this to generate random type of string.

8. Create a function named as generateRandomColor(). In this function we would use Color function Color.fromARGB() with random number generate object and generate color code between 0 to 256. After generating color we would store the color in Color variable using State.

9. Create Widget Build are and here we would make Scaffold widget and use backgroundColor property of scaffold widget to set background color. We would also make a Raised Button and call the above function on button click event.

10. Complete source code for main.dart file:

Screenshots:

Flutter Dynamically Generate Random Background Color Dart Example

Flutter Dynamically Generate Random Background Color Dart Example Flutter Dynamically Generate Random Background Color Dart Example

Leave a Reply

Your email address will not be published.