How to get a random number from range in dart?

前端 未结 9 1748
情深已故
情深已故 2021-01-03 17:13

How does one get a random number within a range similar to c# Random.Next(int min, int max);

相关标签:
9条回答
  • 2021-01-03 18:07

    It can be achieved exactly as you intended by creating extension on int to get random int value. For example:

    import 'dart:math';
    
    import 'package:flutter/foundation.dart';
    
    extension RandomInt on int {
      static int generate({int min = 0, @required int max}) {
        final _random = Random();
        return min + _random.nextInt(max - min);
      }
    }
    

    And you can use this in your code like so:

    List<int> rands = [];
    for (int j = 0; j < 19; j++) {
      rands.add(RandomInt.generate(max: 50));
    }
    

    Note that static extension methods can't be called on type itself (e.g. int.generate(min:10, max:20)), but instead you have to use extension name itself, in this example RandomInt. For detailed discussion, read here.

    0 讨论(0)
  • 2021-01-03 18:07

    Generates a random integer uniformly distributed in the range from [min] to [max], both inclusive.

    int nextInt(int min, int max) => min + _random.nextInt((max + 1) - min);
    
    0 讨论(0)
  • 2021-01-03 18:12

    To generate a random double within a range, multiply a random int with a random double.

    import 'dart:math';
    Random random = new Random();
    int min = 1, max = 10;
    double num = (min + random.nextInt(max - min)) * random.nextDouble();
    
    0 讨论(0)
提交回复
热议问题