从昨天开始,我一直在为此苦苦挣扎-我正在标签控制器(ScreenTabs)中创建新的ScopedModel obj,然后通过包装每个包装将其传递给BottomNavigationBar(第一代后代,例如:ScreenBook)中的多个标签标签为ScopedModelDescendant。到目前为止,一切都很好-一切都按预期进行。
问题出现了,当在我的一个标签中,我想导航到它的子级(例如第二级后代,例如:ScreenBookDetails)并在其中使用ScopedModel时。我已经尝试使用ScopedModelDescendant和ScopedModel.of(context),但没有运气-得到错误:每次都找不到正确的ScopedModel。
我的代码(为简洁起见,略过):
...
class ScreenTabsState extends State<ScreenTabs> {
ModelTabs modelTabs = ModelTabs(); //new Model object
var screens = [new ScreenHome(),new ScreenBook(),];
@override
Widget build(BuildContext context) {
return ScopedModel<ModelTabs>(
model: modelTabs,
child: Scaffold(...)
body: Builder (builder: (context) => Container(child:
screens.elementAt(selectedIndex),)),
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedIndex,
items: [...],
onTap: onTabTapped,
),)...}
...
class ScreenBookState extends State<ScreenBook> {
@override
Widget build(BuildContext context) {
return new Scaffold(
body: ScopedModelDescendant<ModelTabs>(builder: (context, child, model) {
print(TAG + "model status:" + model.status.toString());
return model.status == Status.LOADING ? MyCircularProgressIndicator() :
Builder (builder: (context) =>
Card(...
child: InkWell(
onTap: (){
Navigator.of(context).pushNamed("/ScreenBookDetails");},))}}
...
class ScreenBookDetailsState extends State<ScreenBookDetails>{
@override
Widget build(BuildContext context) {
return Scaffold(
body: ScopedModelDescendant<ModelTabs>(builder: (context, child, model) {
print(TAG + "scoped model status: " + model.status.toString()); //Error: Could not find the correct ScopedModel.
return model.status == Status.LOADING ? MyCircularProgressIndicator() : Builder(builder: (context) => Column(...)
...
有人可以给我指出解决这个问题的正确方法吗?我是Dart和Flutter的新手,所以可能有些不清楚的原因,因为我在ScreenSplashScreen中创建ScopedModel obj时遇到了类似的问题,然后导航到ScreenLogIn并尝试在其中使用它。
谢谢! :)
答案 0 :(得分:0)
最后找到了如何在ScopedModel的Github支持下处理包括Navigator在内的ScopedModel的方法-关键是在build(BuildContext)之外创建一个ScopeModel实例,然后将该实例通过下一个屏幕的构造函数传递,例如:
class HomePage extends StatelessWidget {
SampleScopedModel model = SampleScopedModel();
@override
Widget build(BuildContext context) {
return ScopedModel<SampleScopedModel>(
model: model,
child: Scaffold(
body: Container(),
floatingActionButton: FloatingActionButton(onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NextPage(model))
);
}),
),
);
}
}
class NextPage extends StatelessWidget {
final SampleScopedModel model;
NextPage(this.model);
@override
Widget build(BuildContext context) {
return ScopedModel<SampleScopedModel>(
model: model,
child: Scaffold(
body: ScopedModelDescendant<SampleScopedModel>(
builder: (context, child, model) {
return Text(model.payload.toString());
})
),
);
}
}