Flutter learning record-routing, package, resource management

Continue with the last chapter to build a development environment . This chapter learns about the management of routing, packages, and resources in Flutter.

1. Route management

The route in Flutter is called route, which can be understood as the activity in Android. Route management refers to jumps, value transfers, and return data between routes. Mainly controlled by Navigator, Navigator is a routing management component, which provides methods to open and exit routing pages. Navigator manages the active routing collection through a stack. Usually the page displayed on the current screen is the route at the top of the stack. Navigator provides a series of methods to manage the routing stack, here we only introduce the two most commonly used methods:

Future push (BuildContext context, Route route)
puts the given route on the stack (that is, opens a new page), the return value is a Future object, used to receive the return data when the new route is pushed out of the stack (that is, closed).

bool pop (BuildContext context, [result])
routes the top of the stack out of the stack, and the result is the data returned to the previous page when the page is closed.

1.1 Route Jump

For example, we want to jump to a route called New Route, the basic writing is like this:

NavigatorState navigatorState = Navigator.of(context);
prefix0.MaterialPageRoute materialPageRoute = new MaterialPageRoute(builder: (context){return new NewRoute();});
navigatorState.push(materialPageRoute);
//这段代码和下面的Android中的启动一个Activity很像
Intent intent = new Intent();
intent.setClass(this,MainActivity.class);
startActivity(intent);

Let's look at the difference between shorthand:

Navigator.of(context)
      .push(new MaterialPageRoute(builder: (context) {
   return new NewRoute();
}));
----------------------------------------------------------------
startActivity(new Intent(this,MainActivity.class));

But it is still very troublesome to write this way. There is also a packaged way to start an activity in Android. Look at the packaged code:

ActivityUtils.startActivity(MainActivity.class);
这样来说一行代码就能用普通方式启动一个activity。

Then there is such a simple way to start in Flutter, which is named routing. The so-called named route is to give the route a name first. When we want to start the route, we can start the route based on this name. Here is how to implement the code:

return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      //注册路由表
      routes: {
        "路由名称": (context) => new NewRoute(),
        --省略其他路由注册
      },
    );

The routes in the above code are actually a Map, the key is the name of the route, and it is a string; the value is a builder callback function, which is used to generate the corresponding route widget. When we open a new route by the route name, the application will find the corresponding WidgetBuilder callback function in the routing table according to the route name, and then call the callback function to generate the route widget and return. So let's see how easy it is to start a named route:

Navigator.pushNamed(context, “路由名称”);

One line of code is enough, it's very simple.

1.2 Routing by value

How to pass data when starting a route?
Look at the official function:

 static Future<T> pushNamed<T extends Object>(
    BuildContext context,
    String routeName, {
    Object arguments,
   }) {
    return Navigator.of(context).pushNamed<T>(routeName, arguments: arguments);
  }

In fact, it is the pushNamed function above. The first parameter is the context of the context, the second parameter is the name of the route to start, and the third parameter is the data to be passed. See how to achieve it:

Navigator.pushNamed(context, "路由名称",arguments: "要传递的数据");

Is to add a parameter, this parameter can be string can be int, as long as it is a subclass of object. How does the started route receive the past data, see the code:

class 路由名称 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 下面这行代码就是接收传递数据的代码。
    var data = ModalRoute.of(context).settings.arguments;
   --省略其他代码
}

1.3 Return of routing data

If you start a route and receive the data passed back when the route is closed, how to achieve it. At this time, I used the pop function I started with.
Look at the official website code:

static bool pop<T extends Object>(BuildContext context, [ T result ]) {
   return Navigator.of(context).pop<T>(result);
}

This function is to remove the route at the top of the stack, that is, the current page, to the stack. The first parameter is the context, and the second parameter is the data to be returned. Look at the specific implementation:

RaisedButton(
     onPressed: () => Navigator.pop(context, "NewRoute返回的数据"),
     child: Text("返回"),
)

In this way, the route will be closed and the data will be returned. How to receive the returned data is also very simple. Just change the code started earlier, see the code:

onPressed: () async {
       var pushNamed = await Navigator.pushNamed(
       context, StringsConst.ROUTE_NEW,
       arguments: "来自main的数据");
       print("NewRoute返回的数据:$pushNamed");
}

Here async / await is used to wait for the page to close, and the pushNamed function will return a var, which is the data returned by the route.
Note: This method will only return data when you click the return button you added. Clicking the return on the AppBar or the return button that comes with the phone returns the previous route. No data can be received. How to achieve no matter how to return The data is returned, which is not mentioned in the book. I will see if there is any other way later.

1.4 Start a new route and close the current route

If you want to start a new route and close the current route, use any of the following three functions:

Navigator.of(context).pushReplacementNamed("路由名称");
 --------------------------------------------------------------------------------------                       
Navigator.of(context).pushReplacement(
    new MaterialPageRoute(builder: (context) {
  return new NewRoute();
}));
---------------------------------------------------------------------------------------                        
Navigator.popAndPushNamed(context, "路由名称");

1.5 Start a new route and close all previous routes

There is another situation, that is, when the user logs out, the route to re-login, so we need to close all existing routes, and start the login route, then use the following function:

Future<T> pushNamedAndRemoveUntil<T extends Object>(
    String newRouteName,
    RoutePredicate predicate, {
    Object arguments,
  }) {
    return pushAndRemoveUntil<T>(_routeNamed<T>(newRouteName, arguments: arguments), predicate);
  }

The first parameter: the name of the route to start.
The second parameter: It is not clear for the time being.
The third parameter: the data to be passed.
Look at the specific implementation code:

Navigator.of(context).pushNamedAndRemoveUntil("路由名称", (Route<dynamic> route) => false);

Another function is to close all routes:

void popUntil(RoutePredicate predicate) {
   while (!predicate(_history.last))
     pop();
}

2 Package management

Packages actually refer to some public libraries or SDKs. If we want to use these public packages, we need to have a unified management of these packages. Before introducing package management, first introduce the pubspec.yaml file in Flutter. This file is the configuration file of the project to manage and configure the project and the package. See what the default code in this file means:

# 应用或包名称。
name: first_flutter_app

# 应用或包简介、描述。
description: A new Flutter application.

# 应用或包的版本号。
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

# 应用或包依赖的其它包或插件。
dependencies:
  flutter:
    sdk: flutter

  # 类iOS风格图标
  cupertino_icons: ^0.1.2
  # 常用英文单词以及一些实用功能
  english_words: ^3.1.5

# 开发环境依赖的工具包(而不是flutter应用本身依赖的包)。
dev_dependencies:
  flutter_test:
    sdk: flutter


# flutter相关的配置选项。
flutter:

  uses-material-design: true

The above are some simple introductions, among them: english_words: ^ 3.1.5. It is a public package we use.
These packages are all managed in pub.dev , we can find the packages we need here.
For example, english_words:
Insert picture description here
Example is an example of how to install.
Step 1: Add english_words: ^ 3.1.5 to pubspec.yaml.
Step 2: Click pub get in the upper right corner.
The third step: guide the package in the route used: import 'package: english_words / english_words.dart'.

3 Resource management

3.1 Picture adaptation

Resource management refers to the management of some icons, pictures, fonts, html, etc. Here is a brief introduction to the management of icons, and the rest will be put into practical use later to learn how to use them.
Picture resource management is actually registered in pubspec.yaml, Flutter will choose to load different pictures according to the pixel density of the device screen, how to manage pictures of different sizes, the system will choose the correct picture, create a different in assets The magnification folder is used to store pictures of corresponding sizes, as shown in the figure:
Insert picture description here
Then register in pubspec.yaml:
Insert picture description here
Then you can use it, you do n’t need to write 2x \ 3x, the system will automatically choose the corresponding picture according to the resolution:

Image.asset(
     "assets/wxr.jpg",
     width: 200,
     height: 200,
     fit: BoxFit.cover,
),

3.2 Modify APP icon and start page

Android needs to replace the icon file in the picture to
Insert picture description here
modify the icon of the APP. IOS needs to replace the file in the picture below to modify the APP icon:
Insert picture description here
Android needs to modify the file in the picture below to
Insert picture description here
modify the startup page : iOS needs to modify the file in the picture below to modify the startup page:
Insert picture description here

Published 6 original articles · received 1 · views 440

Guess you like

Origin blog.csdn.net/qq_35809004/article/details/105597656