To generate a random UUID in Dart, you can make use of the built-in UUID package. This package provides a set of utilities for creating, comparing, and manipulating UUIDs.
import 'package:uuid/uuid.dart'; void main() { var uuid = Uuid().v4(); print(uuid); }
The code above uses the `Uuid` class from the `uuid` package and calls its `v4` method to generate a random UUID. The generated UUID is then printed to the console.
If you need to generate a UUID based on the current timestamp, you can use the `v1` method from the `uuid` package. This method generates a version 1 UUID which includes the timestamp information.
import 'package:uuid/uuid.dart'; void main() { var uuid = Uuid().v1(); print(uuid); }
By calling the `v1` method, a time-based UUID is generated, and the value is then printed to the console.
Another way to generate a random UUID in Dart is to use the `uuid` package with the `random` extension. This method allows you to generate a version 4 UUID, which is based on random numbers.
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid_util.dart'; void main() { var uuid = Uuid().v4(options: {'rng': UuidUtil.cryptoRNG}); print(uuid); }
In the code above, the `v4` method of the `Uuid` class is called, and the `options` parameter is passed to use the `cryptoRNG` random number generator. This ensures that the generated UUID is truly random.
Generating UUIDs in Dart can be achieved using various methods provided by the `uuid` package. Whether you need a random UUID or a time-based UUID, there is a suitable method available. By following the examples in this tutorial, you can easily generate UUIDs for your Dart applications.