Routing value transfer method in Flutter

Record some experience in the development process of Flutter.


Flutter development environment

 Today, I sorted out the way of routing and passing values ​​in the development process of Flutter.

During the Flutter development process, the steps to use routing are as follows: first register the next routing list. Then set up an initial route (initialRoute). code show as below:

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        "/":(context)=>const MyHomePage(title: 'Flutter路由传值方式'),
        "/second":(context)=>const SecondPage(content: '',),
        "/third":(context)=>const ThirdPage(content: '你好',),
        "/four":(context)=>const FourPage()
      },
      // home: const MyHomePage(title: 'Flutter路由传值方式'),
    );
  }
}

1. Routing jump

1. Pass the value when you don’t need to pass the value

Refer to the registration method of foutr

 "/four":(context)=>const FourPage()
 

2. Routing jump transfer value

1. Pass the value directly when building the route initialization

You can refer to the route registration method of FourPage

        "/third":(context)=>const ThirdPage(content: 'Hello',),
 

This method is not very flexible, because in most development scenarios, we know the value to be passed to the next page before jumping.

At this time, we can pass the value by setting the entity class

2. Build entity class to pass value

We can look at the pushNamed class. Among them, argument is used to pass parameters. We can build a class to pass values, which will be more flexible.

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

We can first declare a Todo class and pass a title to the next page.

class Todo{
  String title;
  Todo(this.title);
}

The click event of the button is as follows:

Navigator.pushNamed(context, "/four",arguments: Todo("content"));rran

Then we use the ModalRoute.of(context)!.settings.arguments method to parse the passed parameters. code show as below:

final Todo arguments = ModalRoute.of(context)!.settings.arguments as Todo; 
print('Receive the value passed from the second page: ${arguments.title}');

2. Complete demo address


Guess you like

Origin blog.csdn.net/ZCC361571217/article/details/127174639