redux - 如何在 redux flutter app state 中定义对象并访问属性?

标签 redux dart flutter

我在初始状态下定义了一个对象,但是当我尝试检查状态时我得到 null,这是我的 AppState:

@immutable
class AppState {
  final bool isLoading;
  final int bottomNavIndex;
  final Poscomp poscomp;

  AppState({this.isLoading = false, this.poscomp, this.bottomNavIndex});

  factory AppState.loading() => AppState(
        isLoading: true,
        poscomp: Poscomp(exams: []),
        bottomNavIndex: 0,
      );

  AppState copyWith({
    bool isLoading,
    Poscomp poscomp,
    int bottomNavIndex,
  }) {
    return AppState(
      isLoading: isLoading ?? this.isLoading,
      poscomp: poscomp ?? this.poscomp,
      bottomNavIndex: bottomNavIndex ?? this.bottomNavIndex,
    );
  }
}

Poscomp的定义:

@immutable
class Poscomp {
  final List<Exam> exams;

  Poscomp({this.exams = const []});

  Poscomp copyWith({List<Exam> exams}) {
    return Poscomp(
      exams: exams ?? this.exams,
    );
  }

  @override
  int get hashCode => exams.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Poscomp &&
          runtimeType == other.runtimeType &&
          exams == other.exams;

  @override
  String toString() {
    return 'Poscomp{exams: $exams}';
  }
}

当我尝试访问状态的其他属性时,它工作正常,但对象始终返回 null。

最佳答案

显然,当我们分派(dispatch)一个操作时,其他没有reducer的属性被重新定义为null,那么我需要做的是:

为该对象定义一个 reducer :

import 'package:computeiro/store/models/index.dart';
import 'package:computeiro/store/reducers/index.dart';

AppState appReducer(AppState state, action) {
  return AppState(
    isLoading: loadingReducer(state.isLoading, action),
    poscomp: poscompReducer(state.poscomp, action), //HERE
    bottomNavIndex: bottomNavReducer(state.bottomNavIndex, action),
  );
}

Poscomp定义一个新的构造函数:

factory Poscomp.init() => new Poscomp(
      exams: [Exam(question: 'What is somethine?', answer: Answer.A)]);

并在AppState中调用它:

factory AppState.initial() => new AppState(
        isLoading: true,
        poscomp: Poscomp.init(),
        bottomNavIndex: 1,
      );

关于redux - 如何在 redux flutter app state 中定义对象并访问属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54611378/

相关文章:

javascript - keepUnusedDataFor 和 refetchOnMountOrArgsChange 之间有什么区别?

javascript - 在 redux 应用程序中同步数据和离线功能

reactjs - react /Mocha 测试 : can't find imported components

firebase - Fire Storage Exception([firebase_storage/unauthorized] 用户无权执行所需的操作。)(我的规则是允许读/写)

regex - Flutter:如何指定电子邮件验证期间显示的确切字符

flutter - 更新flutter后启动黑屏

reactjs - 在哪里存储 Class 实例以实现 Redux 中的可重用性?

json - 如何在 flutter 中发送多部分请求中的对象列表?

flutter - 如何从 Streambuilder 订购项目

flutter - 使用 super.key 和 (Key? key) : super(key: key) in flutter 有什么区别