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

4 Comments

  1. First, this is the best website that solves my all problems in flutter.
    I requested that tell me the code of the random number in a specific range in which I can describe min and max value.

    • Thanks for appreciating my work Noman. Yes I’ll surely make a new tutorial regarding to your query 🙂 .

  2. And view the numbers in the app?

    • You can make a Text widget and store the random number into State, Now when you create a Random number store into state and on the Text it will update automatically.

Leave a Reply

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