【发布时间】:2021-10-01 23:13:09
【问题描述】:
我目前在使用 Flutter 2.0 Navigator API 时遇到了一些数据竞争错误。我的商店是用 MobX 实现的,并通过Provider 传递下来。之后,我在全局存储上拉一个Observer,然后每次我的全局存储更新时重新更新Navigator(用于路由)。但是,在我点击WinnerPage 的顶部后退箭头之前,一切正常。它在屏幕上显示以下错误,并在稍后立即闪回正常:
Unexpected null value.
The relevant error-causing widget was WinnerView
因此,为了尝试进一步调试,我了解到当按下返回按钮时,winner 的值瞬间为null(来自Navigator 中的onPopPage),这会弹出状态。有谁知道是否有解决此问题的方法?这是我所有的代码:
商店
class GlobalStore extends Store {
@observable
String? winner;
@action
void setWinner(String? newWinner) => winner = newWinner;
}
应用设置
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "MyApp",
home: Provider<GlobalStore>(
create: (_) => GlobalStore(),
child: Observer(builder: (context) {
final store = Provider.of<GlobalStore>(context);
return Navigator(
pages: [
FooPage(),
if (store.winner != null)
WinnerPage()
],
onPopPage: (route, result) {
if (!route.didPop(result)) {
return false;
}
store.setWinner(null);
return true;
}
);
}),
)
);
}
}
Foo 页面(默认)
class FooPage extends Page {
const FooPage() : super(key: const ValueKey('Foo Page'));
Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this, builder: (BuildContext context) => FooView());
}
}
class FooView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final store = Provider.of<GlobalStore>(context);
return Scaffold(
body: TextButton(
child: const Text('Hello, world!'),
onPressed: () {
store.setWinner("You!");
}
)
);
}
}
获奖者页面
class WinnerPage extends Page {
const WinnerPage() : super(key: const ValueKey('Winner Page'));
Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this, builder: (BuildContext context) => WinnerView());
}
}
class WinnerView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final store = Provider.of<GlobalStore>(context);
final winner = store.winner!; // error here!
return Scaffold(
appBar: AppBar(),
body: Column(children: [Text('${winner} is the winner!')]));
}
}
【问题讨论】: