Navigation with parameters

WubaNovember 19, 2022About 2 min

This article will explain to you how to jump between two dynamic pages and how to pass parameters.

image.png

Suppose there are two dynamic pages: PageOne and PageTwo.

We are now going to implement the jump from PageOne to PageTwo while passing some parameters.

The implementation steps are as follows:

step1. Define the route

Add a public jump path in the routes of main.dart:

void main() {
  // runApp(MyApp());

  WidgetsFlutterBinding.ensureInitialized();

  FairApp.runApplication(
    _getApp(),
    plugins: {},
  );
}

dynamic _getApp() => FairApp(
  modules: {},
  delegate: {},
  child: MyApp(),
);

/// Get the parameters passed by the route
dynamic _getParams(BuildContext context, String key) =>
    (ModalRoute.of(context)?.settings.arguments is Map) ? (ModalRoute.of(context)?.settings.arguments as Map)[key] : null;

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        /// Register public routes
        routes: {
          'fair_page_two': (context) => FairWidget(
              path: _getParams(context, 'path'),
              data: {'fairProps': jsonEncode(_getParams(context, 'data'))}),
        },
          
        ......
  }
}

The target page still needs to be loaded using FairWidget.

step2. Use Navigator.pushNamed() to jump

At present, the jump between dynamic pages can only be jumped by using Navigator.pushNamed(), that is, the way of named routes.

The jump parameter needs to pass the bundle path of the target page. Generally, the key is specified as path, such as: 'path': 'assets/bundle/lib_page2page_page_two.fair.json'

If you need to pass values ​​to dynamic pages, you must use the data in the Map structure, and the key is generally specified as data, such as: 'data': {'title': 'PageTwo'}

The code reference is as follows:

()
class PageOne extends StatefulWidget {
  const PageOne({Key? key}) : super(key: key);

  
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('PageOne'),
        ),
        body: Container(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Text('Click the button in the lower right corner to jump to the next page'),
            )
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            /// Jump to dynamic page
            Navigator.pushNamed(context, 'fair_page_two', arguments: {
              'path': 'assets/bundle/lib_page2page_page_two.fair.json',
              'data': {'title': 'PageTwo'}
            });
          },
          tooltip: 'Increment',
          child: const Icon(Icons.arrow_forward_sharp),
        )
    );
  }
}

step3. Receive parameters

A variable needs to be defined to receive a parameter of type Map: dynamic fairProps

()
class PageTwo extends StatefulWidget {
  PageTwo({Key? key,this.fairProps}) : super(key: key);

  dynamic fairProps;

  
  _PageTwoState createState() => _PageTwoState();
}

class _PageTwoState extends State<PageTwo> {
  ()
  var fairProps;

  
  void initState() {
    super.initState();
    fairProps = widget.fairProps;
  }

  String getTitle() {
    return fairProps['title'];
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          /// If you need to splicing strings, you can splicing them in the build() method. It is not recommended to use getTitle()
          /// String concatenation in the method
          title: Text('Parameter: ${getTitle()}'),
        ),
        body: Container(
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Text('xxxxx'),
            )
        ),
    );
  }
}

If the received parameters need to be concatenated with strings, it is recommended to do it directly in the build() method.

Last update:
Contributors: sunzhe03