我的应用有两个屏幕,我想通过按按钮将按钮从第一屏幕推向第二屏幕。
I have app with two screens, and I want to make push from 1st to second screen by pressing button.
屏幕1
import 'package:flutter/material.dart'; import './view/second_page.dart'; void main() => runApp(new MyApp()); class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return new MainScreen(); } } class MainScreen extends State<MyApp> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( appBar: new AppBar( title: new Text("Title") ), body: new Center( child: new FlatButton(child: new Text("Second page"), onPressed: () { Navigator.push(context, new MaterialPageRoute( builder: (context) => new SecondPage())) } ) ) ) ); } }屏幕2
import 'package:flutter/material.dart'; class SecondPage extends StatefulWidget { @override State<StatefulWidget> createState() { return new SecondPageState(); } } class SecondPageState extends State<SecondPage> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Title"), ), body: new Center( child: new Text("Some text"), ), ); } }推未发生,我知道了
在处理手势时引发了以下断言:导航器操作请求的上下文不包含导航器。 用于从导航器推送或弹出路由的上下文必须是作为导航器小部件的后代的小部件的。
The following assertion was thrown while handling a gesture: Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
引发了另一个异常:请求的导航器操作在不包含导航器的上下文中。
Another exception was thrown: Navigator operation requested with a context that does not include a Navigator.
出什么问题了?
推荐答案将Flutter中的小部件想象成一棵树,上下文指向使用build函数构建的任何节点。就您而言,您有
Think of the widgets in Flutter as a tree, with the context pointing to whichever node is being built with the build function. In your case, you have
MainScreen <------ context --> MaterialApp (--> Navigator built within MaterialApp) --> Scaffold --> App Bar --> ... --> Center --> FlatButton因此,当您使用上下文查找导航器时,将使用上下文
So when you're using the context to find the Navigator, you're using a context for the MainScreen which isn't under the navigator.
您可以创建一个新的Stateless或Stateful Widget子类来包含Center + FlatButton,因为其中的构建函数将而是指向该级别,或者您可以使用 Builder 并定义 builder 回调(具有指向Builder的上下文)以返回Center + FlatButton。
You can either make a new Stateless or Stateful Widget subclass to contain your Center + FlatButton, as the build function within those will point at that level instead, or you can use a Builder and define the builder callback (which has a context pointing at the Builder) to return the Center + FlatButton.
更多推荐
Flutter Navigator无法正常工作
发布评论