Flutter freezed default value

Flutter Freezed Default Value

When using Freezed package in Flutter, you can provide default values for fields in generated models. This allows you to create instances of those models with default values for fields that are not explicitly set.

To define a default value for a field, you need to use the `@Default` annotation in your Freezed model. Here’s an example:

    
      import 'package:freezed_annotation/freezed_annotation.dart';

      part 'my_model.freezed.dart';

      @freezed
      abstract class MyModel with _$MyModel {
        const factory MyModel({
          @Default('John Doe') String name,
          @Default(25) int age,
        }) = _MyModel;
      }
    
  

In the above example, the `name` field has a default value of `’John Doe’`, and the `age` field has a default value of `25`. This means that if you create an instance of `MyModel` without explicitly setting values for these fields, they will be initialized with their default values.

Here’s how you can create an instance of `MyModel`:

    
      MyModel myModel = MyModel(); // fields will be initialized with default values
      print(myModel.name); // Output: John Doe
      print(myModel.age); // Output: 25
    
  

As shown in the above example, when you create an instance of `MyModel` without providing values for the fields, they are initialized with their default values.

Leave a comment