Category

Flutter

Category

4 Ways To Generate Random Number In Flutter

Hi, Welcome to AndroidRide.

Random numbers have a big role in our daily life. But we really don’t think that much about that.
They are used in computer encryption, gambling, and lotteries and many more.

So today, you will learn how to generate random number in dart using a Flutter app.

Let’s start…

  • First of all, we will use Random class from dart:math. So import it that first

import 'dart:math';

Let’s create a project.

1. How To Generate Random Number using Random?

 
 

  Random random = Random();

 _randomNumber1 = random.nextInt(50);

  • In this example, _randomNumber1 value will between 0 to 4950 will not be included.
  • You need to provide the maximum value. Then it will generate values between 0 and the maximum value.

2. Generate random number using random.secure

 
Random random2 = Random.secure();

_randomNumber2 = random2.nextInt(50);

  • Using Random.secure(), we can create cryptographically generated random number.
  • It also generates random number between 0 to 49, if it fails an Unsupportederror will thrown.

3. Random double value using random.nextDouble


Random random = Random();
_randomNumber3 = random.nextDouble() * 50;

  • In this example, we will generate double values, it will not include 50.0000

4. Generate random number in range

var min = 1;
var max = 6;

_randomNumber4 = min + random.nextInt(max - min);

  • If you want to generate random number in range, use this technique.
  • In this example, it generates values – 1 to 5.
  • it will not generate 6.

flutter random number
Let’s create a final example which uses all above ways, here I have added 4 buttons to execute each methods.

When you click on it, everyone in them will generate random number and show it in Text.

Full Source Code


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

void main() {
  runApp(const MyHomePage());
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextStyle style = const TextStyle(
    fontSize: 25,
    fontWeight: FontWeight.bold,
  );

  int _randomNumber1 = 0;
  int _randomNumber2 = 0;
  double _randomNumber3 = 0.0;
  int _randomNumber4 = 0;

  Random random = Random();
  Random random2 = Random.secure();

  void _generateRandomNumber1() {
    setState(() {
      _randomNumber1 = random.nextInt(50);
    });
  }

  void _generateRandomNumber2() {
    setState(() {
      _randomNumber2 = random2.nextInt(50);
    });
  }

  void _generateRandomNumber3() {
    setState(() {
      _randomNumber3 = random.nextDouble() * 50;
    });
  }

  void _generateRandomNumberInRange() {
    var min = 1;
    var max = 6;

    setState(() {
      _randomNumber4 = min + random.nextInt(max - min);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Random number generator'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '$_randomNumber1',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber1,
                child: const Text('Generate Random number - 1'),
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                '$_randomNumber2',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber2,
                child: const Text('Generate Random number - 2'),
              ),
              const SizedBox(
                height: 15,
              ),
              Text(
                '$_randomNumber3',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumber3,
                child: const Text('Generate Random number - 3'),
              ),
              Text(
                '$_randomNumber4',
                style: style,
              ),
              ElevatedButton(
                onPressed: _generateRandomNumberInRange,
                child: const Text('Generate Random number - 4'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

If you like this post, please share it with your family and friends.
Thank you.

Please disable your adblocker or whitelist this site!