There are two routes that can be used to jump and transfer values between pages in Flutter:
- The basic routing
- Named route
The official word is static and dynamic routing, but I’m used to it, so let’s just say that!
The basic routing
Basic jump
A jump to a basic route uses push to jump to the specified page, and then pop back to the original page
But when you jump to the past, there will be a default back arrow button, click to go back
Start coding
Dart file I referenced the home.dart file in the main.dart file and there’s a button in the home.dart file that jumps to the details page when I click
Note: If usedstl
The generated static control cannot use jump buttons
Dart file code:
//Home.dart import 'package:flutter/material.dart'; import './Detail.dart'; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return Scaffold( body: Column(children: <Widget>[RaisedButton(child: Text(' skip to details ')), onPressed: Push (MaterialPageRoute(MaterialPageRoute: (context)=>Detail()));},)],); }}Copy the code
When I click the button, I can jump to the Detail page: detail.dart file code:
import 'package:flutter/material.dart'; Class Detail extends StatelessWidget {@override Widget build(BuildContext context) {return Scaffold(// Float button FloatingActionButton: floatingActionButton (Child: Text(' return '), onPressed: (){navigator.of (context).pop(); },), appBar: appBar (title: Text (" detail page "),), the body: the Text (" detail page "),); }}Copy the code
As shown in the figure, there will be a return button by default after jumping over, and you can return after clicking, or you can define a button by yourself, and you can return after clicking by using the POP method
Jump by value
Sometimes we need to pass parameters when we jump, so we need to carry parameters when we jump, which is very simple
We need to define a variable on the page that uses the parameter. Note that we need to set the default value, and use the default value if no value is passed to you and then pass the value to the target page when we jump
Dart file code:
RaisedButton(child: Text(' go to the detail page '), onPressed: // MaterialPageRoute =>Detail(Test:' I am a parameter ') // MaterialPageRoute =>Detail(Test:' I am a parameter ') // MaterialPageRoute =>Detail(Test:' I am a parameter ') (context)=>Detail() ) ); },)Copy the code
It is then received on the target page. If no value is passed, the default value defined above is used
Dart file code:
Class Detail extends StatelessWidget {// You need to define a variable and default value String Test; Detail({this.Test=' no value passed to me '}); @override Widget build(BuildContext context) {return Scaffold(// Float button floatingActionButton: FloatingActionButton(Child: Text(' return '), onPressed: (){navigator.of (context).pop(); },), appBar: appBar (title: Text (" detail page "),), the body: the Text (this) Test),); }}Copy the code
The value is received on return
Sometimes you don’t need to pass values when you jump, but you need to receive values from child components when you return
Use the following example to illustrate:
Dart and getaddress. dart files. Use the getaddress. dart file in mian
Dart file, jump to the Add address page, and then, after selecting the address, take the data directly back to the home page and display it
Code examples:
The main.dart file changes only the controls that need to be rendered
import 'package:flutter/material.dart'; import './address/GetAddress.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Route"), ), body: GetAddress() ), ); }}Copy the code
Note that getting data is asynchronous and the only way to change data with async and await is with setState
Dart file code:
import 'package:flutter/material.dart'; import './AddressList.dart'; class GetAddress extends StatefulWidget { @override _GetAddressState createState() => _GetAddressState(); } class _GetAddressState extends State<GetAddress> {// Define a variable String _ads = ""; @override Widget build(BuildContext context) { return Container( child: Scaffold( appBar: AppBar(title: The Text (' access to harvest address),), body: Center (child: the Column (. / / vertical Center mainAxisAlignment: mainAxisAlignment Center, the children: <Widget>[RaisedButton(// button Theme textTheme: ButtonTextTheme. Primary, color: Theme. Of (context).accentColor, child: Text(' Select shipping address '), // onPressed: Var ads = await navigator.of (context).push(MaterialPageRoute(Builder: (BuildContext context){ return AddressList(); } ) ); setState(() { _ads = ads; }); }, ), The Text (' ${_ads = = ""?" did not look up to the shipping address ": _ads} ')],),),),); }}Copy the code
Click onTap and use POP directly to return to the home page and bring the data back
The AddressList. Dart file code:
import 'package:flutter/material.dart'; class AddressList extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(" mY address "),), body: ListView(padding: EdgeInsets. All (10), children: <Widget>[GestureDetector(onTap: (){//pop = navigator.of (context).pop(' Beijing ');}, // Add event child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.black26) ), child: ListTile( leading: Account_box, color: color.blue,), title: Text(' Beijing ', maxLines: 1, overflow: // SizedBox(height: 10), GestureDetector(onTap: (){//pop Navigator. Of (context).pop(' south ');}, // Add the event to the child component child: Container(decoration: BoxDecoration(border: decoration) Border.all(color: Colors.black26) ), child: ListTile( leading: Icon( Icons.account_box, color: Colors.blue, ), title: Text-align (' line ', maxLines: 1, overflow: textoverflow.ellipsis,),),),), 10), GestureDetector(onTap: (){navigator.of (context).pop(' Shanghai ');}, // Add event to child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.black26) ), child: ListTile( leading: Account_box, color: color.blue,), title: Text(' Shanghai ', maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ), ) ], ), ); }}Copy the code
Named route
Similar to routing in Vue
Basic jump
Dart, Page1. Dart, Page1. Dart, and page3. dart were created for testing
Import the file, configure the path in routes in main.dart (it must be configured in main.dart) and replace the body with the page to render
Dart file code:
import 'package:flutter/material.dart'; import './files/Page1.dart'; import './files/Page2.dart'; import './files/Page3.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Route"), ), body: Main(),), // define routes: {// Use context to specify the context '/page1': (context) => page1 (), '/page2': (context) => Page2(), '/page3': (context) => Page3(), }, ); }}Copy the code
Dart: Write two buttons in the main.dart file to jump to (note one is main.dart and the other is main.dart)
Dart file code:
import 'package:flutter/material.dart'; class Main extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold(Body: Center(Child: Column(children: <Widget>[// define RaisedButton(Child: Text(" jump to Page1")), onPressed: () {// Need to use the pushNamed method Navigator. PushNamed (context, "/page1");},), SizedBox(height: 20), RaisedButton(child: The Text (" jump to Page2 "), onPressed: () {the Navigator. PushNamed (context, "/ Page2");},),),),),),); }}Copy the code
Dart, Page2. Dart, Page3. Dart, Page3.
Dart file code:
import 'package:flutter/material.dart'; class Page1 extends StatefulWidget { @override _Page1State createState() => _Page1State(); } class _Page1State extends State<Page1> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Page1"),), body: Text("Page1",style: TextStyle(fontSize: 40),), ); }}Copy the code
Route extraction jump
Usually when we use named routes, instead of doing this, we pull the routes out individually
Optimize the code above:
Dart file to store the routing rules.
Routes.dart file code:
import 'package:flutter/material.dart'; // Import file import '.. /files/Main.dart'; import '.. /files//Page1.dart'; import '.. /files//Page2.dart'; import '.. /files//Page3.dart'; / / configure routing rules final routes = {'/' : (context) = > the Main (), '/ page1: (context) = > page1 (),'/page2: (context) => Page2(), '/page3': (context) => Page3(), }; // If you want to pull the route out, you have to write the following pile of code, Var onGenerateRoute = (RouteSettings Settings) {// Final String name = Settings. final Function pageContentBuilder = routes[name]; if (pageContentBuilder ! = null) { if (settings.arguments ! = null) { final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context, arguments: settings.arguments)); return route; } else { final Route route = MaterialPageRoute(builder: (context) => pageContentBuilder(context)); return route; }}};Copy the code
Dart is then configured to use:
import 'package:flutter/material.dart'; Dart file import './ Routes/routes.dart '; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( initialRoute: '/', / / configure the default access path onGenerateRoute: onGenerateRoute, / / must add this line, fixed writing); }}Copy the code
Once configured, nothing else needs to be moved, which enables us to pull out the route
Jump by value
Following the code above, what happens when we use a named route and pull out the route to jump to it, and we want to jump to it to pass the value? Very simple
Build on the code above
Dart: Change the button method in the main. dart file to pass the value when jumping, as follows:
Just paste the second jump button and leave the rest of the code untouched
RaisedButton(Child: Text(" go to Page2"), onPressed: () {navigator.pushnamed (context, "/ Page2",arguments: {"id":102}); },),Copy the code
Then change the page2 routing rule in the routes. dart file:
'/page2': (context,{arguments}) => Page2(arguments:arguments),
Copy the code
Dart finally defines the variable, refactors, and receives the passed value:
import 'package:flutter/material.dart'; Class Page2 extends StatefulWidget {// Define a variable final Arguments; / / refactoring Page2 ({enclosing the arguments}); @override _Page2State createState() => _Page2State(); } class _Page2State extends State<Page2> { @override Widget build(BuildContext context) { return Scaffold( appBar: Body: Text("${widget.arguments['id']}",style: TextStyle(fontSize: 40),); }}Copy the code
The source code
Click – >The source address