Flutter 如何生成随机字符串

时间:2021-03-25 13:19:14

标签: string flutter random

你好有谁知道我怎么只能用字母生成字符串。喜欢:

“skdnjfsd”还是“bdfvkjnd”?

我当前的代码:

String _randomString(int length) {
    var rand = new Random();
    var codeUnits = new List.generate(
        length,
            (index){
          return rand.nextInt(33)+89;
        }
    );

    return new String.fromCharCodes(codeUnits);
  }

2 个答案:

答案 0 :(得分:0)

根据@julemand101 的回答,您可以这样做:

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))));```

答案 1 :(得分:0)

在你的代码中实现这个函数

String getRandom(int length){
    const ch = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    Random r = Random();
    return String.fromCharCodes(Iterable.generate(
    length, (_) => ch.codeUnitAt(r.nextInt(ch.length))));
}

然后用长度调用它

原答案:How to generate random string in dart?