Flutter實現(xiàn)路由傳參和參數(shù)回傳(使用命名路由)

第一步配置路由

1 新建routes_mamager.dart文件

//第一步配置路由
final routes = {
  //無參數(shù)傳遞
  '/': (context) => MainContent(),

  //有參數(shù)傳遞,ProductList構(gòu)造
  //final Map arguments;
  //ProductList({Key key, this.arguments}) : super(key: key) {}
  '/product': (context, {arguments}) => ProductList(arguments: arguments)
};

//固定寫法
// ignore: strong_mode_top_level_function_literal_block
var onGenerateRoute = (RouteSettings settings) {
  final String name = settings.name;
  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;
    }
  }
};

2 在Flutter的入口出初始化路由:

@override
Widget build(BuildContext context) {
  // TODO: implement build
  return MaterialApp(
    initialRoute: '/', //初始化的時候加載的路由
    onGenerateRoute: onGenerateRoute,
  );
}

3 使用
傳參有返回值,arguments是傳到下一級的參數(shù),then((value))接收上級返回傳回的參數(shù)

  Navigator.pushNamed(context, '/product', arguments: {'pid': 456})
                .then((value) {//"this is data"
              setState(() {
                name = value;
              });
            });

返回上級界面有返回值

 Navigator.pop(context, "this is data");

無參數(shù)返回值

  Navigator.pushNamed(context, '/product');

替換路由

Navigator.pushReplacementNamed(context, '/');

返回根

Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=> new Tabs()), (route)=> route==null );
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容