flutter导航

Flutter is a Google product used to build hybrid mobile apps with Dart as the coding language.

Flutter是一种Google产品,用于构建以Dart为编码语言的混合移动应用程序。

An app page in Flutter is a Widget, a description of the UI portrayed. To make a legitimate app, you need many of these pages, displaying a multitude of features. It’s all well and fine after you create a new page. But, how do you move between them?

Flutter中的应用程序页面是一个小部件,它描述了所描述的UI。 要制作一个合法的应用程序,您需要其中许多页面,并显示许多功能。 创建新页面后一切正常。 但是,您如何在它们之间移动?

Quite simple: you use the Navigator Class, inbuilt in the Flutter SDK.

非常简单:您可以使用Flutter SDK中内置的Navigator类。

Navigator is yet another Widget that manages the pages of an app in a stack-like format. The full-screen pages are called routes when used in the Navigator. The Navigator works like a normal stack implementation. It comes with two well-known methods, push and pop.

Navigator是另一个以类似堆栈的格式管理应用程序页面的小部件。 在导航器中使用时,全屏页面称为路由。 导航器的工作方式类似于普通的堆栈实现。 它带有两种众所周知的方法pushpop

  1. Push: The push method is used to add another route onto the top of the current stack. The new page is displayed over the previous one.

    Push:push方法用于将另一条路由添加到当前堆栈的顶部。 新页面显示在上一页之上。
  2. Pop: As the Navigator works like a stack, it uses the LIFO (Last-In, First-Out) principle. The pop method removes the topmost route from the stack. This displays the previous page to the user.

    弹出:由于导航器像堆栈一样工作,因此使用LIFO(先进先出)原理。 pop方法从堆栈中删除最顶层的路由。 这将向用户显示上一页。

In this post, I will display:

在这篇文章中,我将显示:

  1. Two ways of navigation and

    两种导航方式
  2. Passing data to the next page.

    将数据传递到下一页。

正常导航。 (Normal Navigation.)

There are two ways to do this:

有两种方法可以做到这一点:

push方法中创建一个新页面 (Creating a new page within the push method)

In this method, a new route is created using the MaterialPageRoute class. A new page (Widget) is created within it. These two creation statements come enclosed in the push method and add this page to the top of the stack.

在此方法中,使用MaterialPageRoute类创建新的路由。 在其中创建一个新页面(窗口小部件)。 这两个创建语句包含在push方法中,并将此页面添加到堆栈的顶部。

To display a simple example, I’m using code from a previous repo and blog post. I edited it to include a button on the CustomCard component. This button uses the push method, while the new route and page are created within it.

为了显示一个简单的示例,我使用了先前回购和博客文章中的代码。 我对其进行了编辑,以在CustomCard组件上包含一个按钮。 此按钮使用push方法,同时在其中创建新的路线和页面。

Widget build(BuildContext context) {  
	return Card(    
    	child: Column(      
        	children: <Widget>[        
            	Text('Card $index'),        
                FlatButton(          
                	child: Text("Press Me"),          
                    onPressed: () {            
                    	Navigator.push(context, MaterialPageRoute<void>(
                        	builder: (BuildContext context) {                
                            	return Scaffold(                  
                                	appBar: AppBar(title: Text('My Page')),
                                    body: Center(                    
                                    	child: FlatButton(
                                        	child: Text('POP'),
                                           	onPressed: () {
                                            	Navigator.pop(context);
                                            },                    
                                        ),                  
                                    ),                
                                );              
                            },            
                        ));          
                    }),    
            ],  
        ));
}
将路线添加到应用的入口点 (Add routes to the apps’ entry point)

In retrospect, apps have many pages, and more often than not, with complex coding. It wouldn’t be easy to keep creating a new page to push into. This is especially true if the page is accessed from many different areas. You might lose track of the code for each of the same route.

回想起来,应用程序有很多页面,而且通常都是复杂的代码。 继续创建要推送的新页面并不容易。 如果从许多不同区域访问页面,则尤其如此。 您可能会忘记同一条路线中每条路线的代码。

So, in the second method, the page is created once but added as a route in the entry point of the app, main.dart. These routes are named like file paths since the root page of the app is the path /.

因此,在第二种方法中,页面仅创建一次,但作为路由添加到应用程序的入口main.dart 。 这些路由的名称类似于文件路径,因为应用程序的根页面是路径/

You first build a new app page, like so:

首先,您需要建立一个新的应用程序页面,如下所示:

class SecondPage extends StatelessWidget {
	@override
	Widget build(BuildContext context) {
		return Scaffold(
			appBar: AppBar(
				title: Text('Second Page'),
			),
			body: Center(
				child: RaisedButton(
					child: Text('Back To HomeScreen'),
					color: Theme.of(context).primaryColor,
					textColor: Colors.white,
					onPressed: () => Navigator.pop(context)),
			),
		);
	}
}

Then, import the new page in the main.dart file and add it to the list of routes inside the MaterialApp constructor.

然后,将新页面导入main.dart文件,并将其添加到MaterialApp构造函数内部的路由列表中。

class MyApp extends StatelessWidget {
// This widget is the root of your application.
	@override
	Widget build(BuildContext context) {
		return MaterialApp(
			title: 'Flutter Demo',
			theme: ThemeData(
				primarySwatch: Colors.green,
			),
			home: MyHomePage(title: 'Flutter Demo Home Page'),
			routes: <String, WidgetBuilder>{
				'/a': (BuildContext context) => SecondPage(),
			});
	}
}

We then edit the onPressed method of the FlatButton in the CustomCard to this:

然后,我们将CustomCard FlatButton的onPressed方法编辑为:

Navigator.pushNamed(context, '/a');

In the above example, the user is redirected to the SecondPage class created as it is the corresponding page to the path /a.

在上面的示例中,用户被重定向到创建的SecondPage类,因为它是路径/a.的对应页面/a.

在页面之间传递数据 (Passing Data between pages)

Now for the last part of the demo, passing data to the next page. Doing so in an easy way requires a mix of both the above-mentioned navigation methods.

现在是演示的最后一部分,将数据传递到下一页。 以简单的方式进行操作需要将上述两种导航方法混合使用。

Both pushNamed and creating a new route inside the push method can be used to pass data to the new page. For the latter, a new page need not be made. The builder parameter of the MaterialPageRoute will now call the constructor of the SecondPage class.

pushNamed和在push方法内部创建新路由都可以用于将数据传递到新页面。 对于后者,不需要创建新页面。 MaterialPageRoute的builder参数现在将调用SecondPage类的构造函数。

Update the SecondPage class to accept the data being passed to it, like so:

更新SecondPage类以接受传递给它的数据,如下所示:

class SecondPage extends StatelessWidget {
	SecondPage({@required this.title});
	final title;
    
	@override
	Widget build(BuildContext context) {
		return Scaffold(
			appBar: AppBar(
				title: Text('Card No. $title'),
			),
			body: Center(...),
		);
	}
}

The FlatButtons’ onPressed method is now edited to:

FlatButtons的onPressed方法现在被编辑为:

Navigator.push(context,
	MaterialPageRoute(
		builder: (context) => SecondPage(title: index)
	)
);

Or this:

或这个:

Navigator.pushNamed( context, '/a',
	arguments: <String, String>{
		'title': index + "",
	},
);

The index of the card is now passed on to the SecondPage class, and is displayed in the AppBar.

卡的索引现在传递到SecondPage类,并显示在AppBar

Thanks for reading! You can find the repo, here.

谢谢阅读! 您可以在此处找到该仓库。

Find the commit for the following changes, here.

此处找到以下更改的提交。

翻译自: https://www.freecodecamp.org/news/how-to-handle-navigation-in-your-flutter-apps-ceaf2f411dcd/

flutter导航

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐