Flutter Tutorials

Flutter app development tutorials


flutter – How to generate random string

main.dart


import 'dart:math';
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      theme: ThemeData(primarySwatch: Colors.amber),
      home: Scaffold(
          appBar: AppBar(
              title: const Text("Flutter - Random String")
          ),
          body: bodyContent()
      ),
    ),
  );
}

bodyContent(){
  const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
      '1234567890';
  String getRandomString([int length = 8]) => String.fromCharCodes(
      Iterable.generate(
          length, (_) => chars.codeUnitAt(
          Random().nextInt(chars.length))
      )
  );

  return Center(
    child: Container(
      color: Colors.black12,
      alignment: Alignment.center,
      height: 200,
      margin: const EdgeInsets.all(16),
      child: Text(
          getRandomString(12),
          style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 30
          )
      ),
    ),
  );
}

More flutter tutorials



About Me

Flutter Developer

Design a site like this with WordPress.com
Get started