How to generate random string in dart?

后端 未结 4 739
旧巷少年郎
旧巷少年郎 2021-01-12 00:37

I want to create a function that generates a random string in dart. It should include alphabets and numbers all mixed together. How can I do that?

相关标签:
4条回答
  • 2021-01-12 00:56

    Found this in a blog article about crypto strings:

    import 'dart:math';
    import 'dart:convert';
    
    String getRandString(int len) {
      var random = Random.secure();
      var values = List<int>.generate(len, (i) =>  random.nextInt(255));
      return base64UrlEncode(values);
    }
    

    The string always ends with ==. I would also assume that it's not the fastest solution. But you don't need third party packages and don't have to declare obscure constants.

    0 讨论(0)
  • 2021-01-12 00:58

    Option A with charCodes:

    import 'dart:math';
    
    String generateRandomString(int len) {
      var r = Random();
      return String.fromCharCodes(List.generate(len, (index) => r.nextInt(33) + 89));
    }
    

    Generates random string using visible characters including special ones.

    Option B with a predefined string:

    import 'dart:math';
    
    String generateRandomString(int len) {
      var r = Random();
      const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
      return List.generate(len, (index) => _chars[r.nextInt(_chars.length)]).join();
    }
    
    0 讨论(0)
  • 2021-01-12 01:01

    I would try this package: https://pub.dev/packages/random_string

    Haven't used it myself but seems to meet your needs.

    It currently has a 99 rating so it should be good.

    0 讨论(0)
  • 2021-01-12 01:13

    Or if you don't want to use a package you can make a simple implementation like:

    import 'dart:math';
    
    void main() {
      print(getRandomString(5));  // 5GKjb
      print(getRandomString(10)); // LZrJOTBNGA
      print(getRandomString(15)); // PqokAO1BQBHyJVK
    }
    
    const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    Random _rnd = Random();
    
    String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
        length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));
    

    I should add that you should not use this code to generate passwords or other kind of secrets. If you do that, please at least use Random.secure() to create the random generator.

    0 讨论(0)
提交回复
热议问题