【发布时间】:2018-12-23 10:07:19
【问题描述】:
我正在使用flutter scoped_model,当我们尝试从子Widget访问ScopedModel时,它能够无误地访问。
但是当我尝试从使用 Navigator.push 加载的 Widget 访问它时,相同的代码无法使用,它给出错误错误:找不到正确的 ScopedModel。
PageModel 在首页声明。
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
class PageModel extends Model {
String title;
static PageModel of(BuildContext context) =>
ScopedModel.of<PageModel>(context);
loadTitle() {
title = 'Old Title ';
}
updateTitle() {
title = 'New Title';
notifyListeners();
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final PageModel model = PageModel();
@override
Widget build(BuildContext context) {
return ScopedModel<PageModel>(
model: model,
child: Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: HomePageBody(),
),
);
}
}
class HomePageBody extends StatefulWidget {
@override
_HomePageBodyState createState() => _HomePageBodyState();
}
class _HomePageBodyState extends State<HomePageBody> {
@override
void initState() {
PageModel.of(context).loadTitle();
super.initState();
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<PageModel>(
builder: (BuildContext context, child, PageModel model) {
return Column(
children: <Widget>[
Text(model.title),
RaisedButton(
child: Text('Edit'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(), fullscreenDialog: true),
);
},
),
],
);
});
}
}
class DetailPage extends StatefulWidget {
@override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Edit Page'),
),
body: RaisedButton(
child: Text('Update'),
onPressed: () {
PageModel.of(context).updateTitle();
},
),
);
}
}
从 DetailPage 当我们调用 PageModel.of(context).updateTitle();出现以下错误,
/flutter (26710): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (26710): The following ScopedModelError was thrown while handling a gesture:
I/flutter (26710): Error: Could not find the correct ScopedModel.
I/flutter (26710):
I/flutter (26710): To fix, please:
I/flutter (26710):
I/flutter (26710): * Provide types to ScopedModel<MyModel>
I/flutter (26710): * Provide types to ScopedModelDescendant<MyModel>
I/flutter (26710): * Provide types to ScopedModel.of<MyModel>()
I/flutter (26710): * Always use package imports. Ex: `import 'package:my_app/my_model.dart';
I/flutter (26710):
I/flutter (26710): If none of these solutions work, please file a bug at:
I/flutter (26710): https://github.com/brianegan/scoped_model/issues/new
【问题讨论】: