【问题标题】:Riverpod state class default valueRiverpod 状态类默认值
【发布时间】:2021-12-06 06:32:24
【问题描述】:

例如我的课程 ProfileModel 有一堆字段
他们中的许多人没有默认值,除非当我从后端获取用户信息时它们正在初始化

对于riverpod,我需要写一些类似的东西

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

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

我知道我需要将 ProfileState.empty() 之类的东西传递给 super() 方法,而不是传递 null

但在这种情况下,我必须为每个 ProfileModels 字段创建默认值

这对我来说听起来很奇怪,我不想为了关心项目中每个模型的空状态或默认状态而伤脑筋

在我的示例中,用户名、年龄等没有默认值
这是纯粹的不可变类

我做错了什么或错过了什么?

或者我可以将模型声明为可空extends StateNotifier&lt;ProfileModel?&gt;

但我不确定这是不是一个好方法

【问题讨论】:

    标签: flutter dart riverpod


    【解决方案1】:

    可以将StateNotifier 与可空模型一起使用。如果您在语义上想要表明该值实际上可以不存在,我会说拥有null 就可以了。

    但是,我通常做的和我认为更好的做法是创建一个包含模型的状态模型,以及与应用可能处于的不同状态相关的属性。

    例如,在从 API 获取模型的数据时,您可能希望在等待获取数据时具有加载状态以在 UI 中显示微调器。 I wrote an article about the architecture that I apply using Riverpod.

    状态模型的一个简单示例是:

    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;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多