Flutter提示之Navigator operation requested with a context that does not include a Navigator
1 、問題
用Flutter寫了頁面跳轉(zhuǎn),提示錯誤如下
Navigator operation requested with a context that does not include a Navigator.
2 、我的代碼
void main() {
runApp(MyApp1());
}
class MyApp1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'open url',
home: Scaffold(
appBar: AppBar(
title: Text('hello flutter'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(
child: Text("go to new page"),
textColor: Colors.blue,
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder:(context) => NewPage()));
},
),
],
),
),
);
}
}
class NewPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("hello word"),
),
body: Center(
child: Text("this is new page"),
),
);
}
}
3、原因
Navigator operation requested with a context that does not include a Navigator.
說明這個context上下文不一致,我們看下Navigator的繼承關(guān)系
class Navigator extends StatefulWidget {
}
但是我的代碼是這樣的
class MyApp1 extends StatelessWidget {
}
我們需要使用StatefulWidget的Context
4、解決辦法
void main() {
runApp(MaterialApp(
title: "Navigation basics",
home: MyApp1(),
));
}
用MaterialApp啟動
class MaterialApp extends StatefulWidget {
***
}
作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)