我在初始状态下定义了一个对象,但是当我尝试检查状态时我得到 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/