Flutter -- static route and dynamic route

Contents of this article

Preface

In the previous section, I explained some knowledge of router, such as the related knowledge of router when explaining Hero animation. In fact, routing is a professional term, that is, interface switching, and jump interface explains route jump. (the figure below shows the implementation effect of dynamic routing)

We mentioned that in the development of Flutter, the management of route is carried out by stack, that is to say, the basic usage is push and pop. In the actual project, it is not so simple, and there are many jumps between pages, which involves the management knowledge of route stack, and the types of route are divided into static route and dynamic route Let's explain the two routes separately.

Static routing

As the name suggests, static routing is used when you know which interface to jump to. For example, in the MaterialApp constructor, we can define the route list. The previous introduction is passed in the runApp method in the main entry function. The specific code is as follows:

import 'package:flutter/material.dart';
import 'package:route_flutter_app/page1.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Static routing',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/page1':(context)=>Page1(title: "Main page",),
        '/page2':(context)=>Page2(title: "Second page",),
        '/page3':(context)=>Page3(title: "Third page",),
        '/page4':(context)=>Page4(title: "Fourth page",),
      },
      onUnknownRoute: (RouteSettings setting){
        String name=setting.name;
        print("No match to route");
        return new MaterialPageRoute(builder: (context){
          return new ErrorPage(title: "No matching pages",);
        });
      },
      home: Page1(title: "Main page",),
    );
  }
}

In the above code, we define the main page through home, and routes defines the routing table. page1234 is our static route, that is, we know in advance which interface we need to use, which is to use this method. The parameters of routes are of Map type.

Special note: MaterialApp also has an attribute, which is initRoute, which we mentioned in the previous chapter. It refers to the default route started by App, that is, the main page. If you use this attribute, you do not need to specify home.

Through the corresponding routing table above, we can directly use the Navigator.pushNamed method to jump. However, for the sake of program preciseness, we can also define an error interface, that is, the onUnknownRoute above, and jump to an error defined interface through the above code to avoid program crash and error and increase user experience.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Page1 extends StatelessWidget{
  final String title;

  Page1({Key key,@required this.title}):super(key:key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("Jump to page2"),
          onPressed: (){
            Navigator.pushNamed(context, "/page2");
          },
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget{
  final String title;

  Page2({Key key,@required this.title}):super(key:key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("Jump to page3"),
          onPressed: (){
            Navigator.pushNamed(context, "/page3");
          },
        ),
      ),
    );
  }
}

class Page3 extends StatelessWidget{
  final String title;

  Page3({Key key,@required this.title}):super(key:key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("Jump to page4"),
          onPressed: (){
            Navigator.pushNamed(context, "/page4");
          },
        ),
      ),
    );
  }
}

class Page4 extends StatelessWidget{
  final String title;

  Page4({Key key,@required this.title}):super(key:key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: Center(
        child: Text(this.title,style: new TextStyle(fontSize: 50,color: Colors.red),)
      ),
    );
  }
}

class ErrorPage extends StatelessWidget{
  final String title;

  ErrorPage({Key key,@required this.title}):super(key:key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: Center(
          child: Text(this.title,style: new TextStyle(fontSize: 50,color: Colors.red),)
      ),
    );
  }

Above are the four jump interfaces and one error interface defined by us. If the codes are all basic codes, we will not explain them much. Here, our implementation effect is shown as follows:

In the onPress of RaisedButton, we can jump to the defined route table interface by calling the method Navigator.pushNamed(context, "/ page4"). Of course, we can also use the previous push method:

Navigator.of(context).push(
	new MaterialPageRoute(
		builder:(context){
			return new Page4()}));

Dynamic routing

Although static routing can jump the interface, in most projects, we need to carry parameters when we jump between the two interfaces, for example, many News apps jump from the list to the News details interface. At this point, dynamic routing works. Let's take a look at the code to see how dynamic routing is implemented. First, we define a News class News used in a list:

class News{
  final String title;
  final String description;
  
  New(this.title,this.description);
}

Here is a news class defined by the editor. The news class has two variables, a title and a details. Then we directly modify the code of page1 on the main page, as shown below:

class Page1 extends StatelessWidget{
  final String title;

  Page1({Key key,@required this.title}):super(key:key);

  final news=List<News>.generate(20, (i)=>News("Journalism $i","Journalism $i Details of"),);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
      ),
      body: ListView.builder(itemBuilder: (context,index){
        return ListTile(
          title: Text(news[index].title),
          onTap: (){
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context)=>NewsDetail(s_new: news[index],),
              )
            );
          },
        );
      },
        itemCount: news.length,
      ),
    );
  }
}

First, a 20 element news list is generated here. A list can be created quickly by the generate method, and then a listView list can be generated by the ListView.builder method. Each list is a ListTile. Through the onTap method, click events are monitored. Here, the clicked news class is passed to the NewsDetail detail interface:

Navigator.push(
    context,
    MaterialPageRoute(
        builder: (context)=>NewsDetail(s_new: news[index],),
    )
);

Next, let's take a look at the settings of our detail interface. The code is as follows:

class NewsDetail extends StatelessWidget{
  final News s_new;

  NewsDetail({Key key,@required this.s_new}):super(key:key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(this.s_new.title),),
      body: Center(
        child: Text(this.s_new.description),
      ),
    );
  }

}

Here is a regular code snippet, which defines a title and displays the details of the news in the middle. Then we implement the operation shown at the beginning of the blog.

114 original articles published, 147 praised, 1.13 million visitors+
His message board follow

Keywords: Attribute

Added by engkeb0i on Sat, 07 Mar 2020 13:23:20 +0200