我有一些 ParentWidget ,使用showModalBottomSheet进行调用。它还由 InheritedWidget (BlocProvider)的后继者包装,以允许ParentWidget的子级访问Bloc。可以以某种方式修改 ChildWidget1 上显示的日期(请参阅InkWell小部件)。然后我切换到 ChildWidget2 (ChildWidget1被销毁),我希望看到在ChildPage1上修改的日期作为ChildPage2日历小部件中的选定日期,但值为 bloc.someDateValue 是空的。
我试图做
bloc.changeDate(...)
当我切换到第二个小部件时,它无济于事。
请帮助,如何强制将日期发送到其他子小部件?
发起人:
showModalBottomSheet(context: context, builder: (context) {
return BlocProvider<ParentBloc>(
child: ParentWidget(),
bloc: ParentBloc(),
);
});
BLoC:
class ParentBloc {
final _dateSubject = BehaviourSubject<DateTime>();
Observable<DateTime> get someDate => _dateSubject.stream;
DateTime get someDateValue => _dateSubject.value;
Function(DateTime) get changeDate => _dateSubject.add;
}
ParentWidget:
//.. somewhere in `build`
...
StreaBuilder<DateTime>(
stream: bloc.someDate, // <-- target date
builder: (context, snapshot) {
Text(snapshot.data),
}
),
...
CoupertinoSegmentControl(
children: {
0, 'Child 1',
1, 'Child 2',
},
onValueChanged: (value) {
setState() {
childIndex = value;
}
},
...
)
...
Container(
child: childIndex == 0 ? ChildWidget1() : ChildWidget2(),
)
ChildWidget 1:
DateTime calcDate() {
return someCalculatedDate;
}
// .. somewhere in `build`
final bloc = BlocProvider.of<ParentBloc>(context);
...
InkWell(
onTap: () => bloc.changeDate(calcDate()); // send date to stream
)
儿童小部件2:
// ... somewhere in `build`
StreamBuilder(
initialData: bloc.someDateValue, // <-- latest changed date is expected
stream: bloc.someDate,
builder: (context, snapshot) {
CalendarCarousel(
selectedDateTime: snapshot.data,
)
}
),