Flutter Dart Generate Random Number on Button Click Example

Random number is useful in many applications where developer wants to generate unique keys or something unique values. In flutter there is a class named as Random which can generate random integer number. We can define the number largest range and the produced number will be in that range. So in this tutorial we would Flutter Dart Generate Random Number on Button click Android iOS Example Tutorial.

Contents in this project Flutter Dart Generate Random Number on Button click in Android iOS Example Tutorial:

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

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

3. Create our main MyApp class extends with Statelesswidget.

4. Create a function named as generateRandomNumber(). In this function we would firstly create object of Random class then use the objectName.nextInt() method to generate random number in given range. We are printing the generated random number on Terminal screen.

5. Creating Widget Build area in MyApp class. Now we would make Scaffold widget -> Center Widget -> Column widget -> Container widget -> Raised Button widget. We would call the generateRandomNumber() function on button click event. So every time when user press the button it’ll generates us a new random number between given range.

6. Complete source code for main.dart file:

Screenshot:

Flutter Dart Generate Random Number on Button Click Example

Flutter Dart Generate Random Number on Button Click Example

Leave a Reply

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