Help us understand the problem. What is going on with this article?

Dartでランダムな文字列を生成する

More than 1 year has passed since last update.

mathパッケージのRandomクラスを使えばよい。

import 'dart:math';

String randomString(int length) {
  const _randomChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const _charsLength = _randomChars.length;

  final rand = new Random();
  final codeUnits = new List.generate(
    length, 
    (index) {
      final n = rand.nextInt(_charsLength);
      return _randomChars.codeUnitAt(n);
    },
  );
  return new String.fromCharCodes(codeUnits);
}

void main() {
  print(randomString(10));
}

なお、暗号論的に安全な乱数を使いたい場合は new Random.secure() を使う。

najeira
Software developer。Google Cloud(特にApp Engine)とFlutterのGoogle Developers Expert。好きな言語はGo。他Flutter/Dart, Android, iOS, Python。
michael-inc
マイケルはコミュニティサービスをつくる会社、「Community Builder」です。インターネットを通して人生がより豊かになるよう、人がつながる場所をつくりつづけます。
https://michael-inc.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away