简体   繁体   中英

Riverpod state class default value

eg I have class ProfileModel with bunch of fields
many of them don't have default values unless they're initialising when I get user info from backend

with riverpod I need to write something like

final profileProvider = StateNotifierProvider((ref) => ProfileState());

class ProfileState extends StateNotifier<ProfileModel> {
  ProfileState() : super(null);
}

I understand I need to pass something like ProfileState.empty() into super() method instead passing null

but in this case I have to invent default values for every ProfileModel s fields

this sounds weird for me, I don't want to break my head to care about empty or default state of EVERY model in project

in my example there are no default values for user name, age etc
this is pure immutable class

what I'm doing wrong or missing?

or I can declare model as nullable extends StateNotifier<ProfileModel?>

but I'm not sure is this a good way

It is fine to use the StateNotifier with a nullable model. If you semantically want to indicate the value can be actually absent, I would say that that having null is alright.

However, what I usually do and what I think is better, is create a state model that contains the model, but also properties that relate to the different states the app could be in.

For example, while fetching the data for the model from an API, you might want to have a loading state to show a spinner in the UI while waiting for the data to be fetched. I wrote an article about the architecture that I apply using Riverpod .

A simple example of the state model would be:

class ProfileState {
  final ProfileModel? profileData;
  final bool isLoading;

  ProfileState({
    this.profileData,
    this.isLoading = false,
  });

  factory ProfileState.loading() => ProfileState(isLoading: true);

  ProfileState copyWith({
    ProfileModel? profileData,
    bool? isLoading,
  }) {
    return ProfileState(
      profileData: profileData ?? this.profileData,
      isLoading: isLoading ?? this.isLoading,
    );
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is ProfileState &&
        other.profileData == profileData &&
        other.isLoading == isLoading;
  }

  @override
  int get hashCode => profileData.hashCode ^ isLoading.hashCode;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM