当前位置: 首页>后端>正文

flutter 使用命名的路由传递

全是学习和搬砖,只为记录部分代码,写项目的时候可以翻看一下
注意事项:使用命名路由的话body部分不能和routes同时存在,可以把body部分放在根部路由 "/"下面
另外如果有带参数的路由的话需要onGenerateRoute获取路由,
pageContentBuilder中的参数arguments 必须和routes中写的一致,不一致会报如图错误*

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


class MyApp extends StatelessWidget {

  MyApp({Keykey});
  Map routes={
    "/":(context)=>RouteNameDemo(),
    "/page":(context)=>DemoPage(),
    "/two":(context,{arguments})=>TwoRoute2(args: arguments,)
  };
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "命名路由",
      // routes: {
      //   "/":(context)=>RouteNameDemo(),
      //   "/page":(context)=>DemoPage(),
      //   "/two":(context,{args})=>TwoRoute2(args: args,)
      // },
      initialRoute: "/",
      onGenerateRoute: (RouteSettings settings){
        //统一处理
        final Stringname=settings.name;
        final FunctionpageContentBuilder=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;
          }
        }
        return null;
      },
    );
  }
}

class RouteNameDemo extends StatelessWidget {
  const RouteNameDemo({Keykey}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("命名路由"),
      ),
      body: ListView(
        children: [
          TextButton(
            onPressed: (){
              Navigator.of(context).pushNamed("/page");
            },
            child: Text("跳转"),
          ),

          TextButton(
            onPressed: () async {
             await Navigator.of(context).pushNamed("/two",arguments: {
                "name":"张三",
                "name1":"张三1",
                "name2":"张三2",
                "name3":"张三3",

              });
            },
            child: Text("跳转带参数"),
          )
        ],
      )
    );
  }
}
flutter 使用命名的路由传递,第1张
9d265b20f014c8bf9d4a477068f9dba9.jpg

接收页面的代码:

class TwoRoute2 extends StatelessWidget {
  final Map args;
  const TwoRoute2({Keykey, required this.args});

  List<Widget> _getListData(){
    List<Widget> data=[];
    for(String str in args.values.toList()){
      data.add(ListTile(
        title: Text(str),
      ));
    }

    return data;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("第二个页面"),
      ),
      body: Scaffold(
        appBar: AppBar(
          title: const Text("路由"),
        ),
        body: ListView(
          children:_getListData(),
        ),
      )
    );
  }
}



https://www.xamrdz.com/backend/3gz1937923.html

相关文章: