Open In App

How to Generate a Random UUID in Flutter?

Last Updated : 01 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter SDK is an open-source software development kit developed by Google. UUID stands for Universally Unique Identifier. There are many situations when we need to use unique identifiers while developing an application, for example, when making a note-taking app, every note should have a unique id attached to it which helps in differentiating it from others.

Approach:

Use the dart package UUID to generate unique identifiers.

Step 1: Navigate to pubspec.yaml file and add the dependency

Open your project in VS Code and navigate to pubspec.yaml file and add the UUID package as a dependency.

 

Step 2: Download the required Packages

Download the complete package by running the below command in VS code terminal.

flutter pub get

Step 3: Complete Code

Syntax:

String uuid = Uuid().v4();

The below example shows the use of the UUID package to generate a random UUID every time the button is clicked.

Dart




import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'UUID Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  String uuid = Uuid().v4(); // Generate a random UUID
  
  void _generateNewUuid() {
    setState(() {
      uuid = Uuid().v4(); // Generate a new random UUID
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('UUID Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(uuid),
            ElevatedButton(
              child: const Text('Generate new UUID'),
              onPressed: _generateNewUuid,
            ),
          ],
        ),
      ),
    );
  }
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads