Flutter how to generate random strings

1,745

Solution 1

implement to your code this function

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

and after call it with length

the original answer : How to generate random string in dart?

Solution 2

As per the answer of @julemand101, you can do this:

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))));```
Share:
1,745
sebi
Author by

sebi

Updated on December 19, 2022

Comments

  • sebi
    sebi over 1 year

    Hello does anyone know how I can only generate Strings with letters. Like :

    "skdnjfsd" or "bdfvkjnd" ?

    my current code :

    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);
      }
    
  • iDecode
    iDecode about 3 years
    Instead of coping the answer, you could have flagged the post as duplicate.