Quick Start

Add to project#

Add the following to your pubspec.yaml:

dependencies:
  chance_dart: ^[version]

dev_dependencies:
  chance_generator: ^[version]
  build_runner: ^[version]

Variable usage#

You can declare a variable and assign the declared variable to any of chance dart methods.

For instance:

import 'chance_dart/chance_dart.dart' as chance;

void main(){
    int number = chance.integer();
    print(number);
}

Annotation usage#

You can generate a random value for annotated variables variable using build_runner.

Firstly you have to create a class with an unnamed constructor. Annotate the class with the ChanceType annotation and then the variables you need to generate values for with the ChanceField parameter.

The ChanceField annotation takes in an important parameter called alias.

ChanceAlias is an enum with the different alias for the values you can generate with chance_dart.

Check out the list of generatable aliases here.

Here is an example of how to use the chance annotation:

import 'package:chance_dart/chance_dart.dart';

part 'user.g.dart';

class User{
  User({
    required this.lastName,
    required this.firstName,
  });
  @ChanceField(
    alias: ChanceAlias.lastName,
  )
  final String lastName;

  @ChanceField(
    alias: ChanceAlias.lastName,
  )
  final String firstName;

  static User generatedUser => generatedModel();
  static List<User> generatedUsers => generatedModels();
}

Steps:#

  • Import the chance_dart package.
  • Add a part path with .g.
  • Create your class and ensure values are added to the constructor.
  • Above each fields, add the ChanceField annotation and pass the alias.
  • The ChanceField annotation also takes in an args paramete of the type Map-String, dynamic. Checkout the list of Chance Aliases and the arguments they can take here.
  • Create two static variables, a List-CurrentClass and the CurrentClass, assign the variables to generatedModels and generatedModel respectively.

After performing the actions above, open an your integrated terminal and run the command below:

dart pub run build_runner build

This should generate a .g file with a data model and a list of data model.

You can use each variables generated by access the static variables. For example:

import 'user.dart'
void main(){
    final listOfUsers = User.generatedUsers;
    final user = User.generatedUser;

    print(listOfUsers);
    print(user);
}

Video Tutorial#

Learn the basics of using Hive in this well-made tutorial by Czar Coming Soon.