我在初始状态下定义了一个对象,但是当我尝试检查状态是否为空时,这是我的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。
答案 0 :(得分:2)
显然,当我们调度一个动作时,其他没有reducer的属性都被重新定义为null,那么我需要做的是:
为该对象定义一个化简器:
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,
);