flutter 入坑 路由跳转带参

夜雨入心

共四个文件

1.routes:

import 'package:flutter/material.dart';
import '../pages/tabbarPages/home_page.dart';//路由页面路径
import '../pages/goods/goodsDtail.dart';//路由页面路径
// 配置路由
final routes = {
  // 前面是路由命名 后面是加载的页面
 '/': (context) => HomePages(), //不用传参的写法
 '/goods/detail': (context,{arguments})=>GoodsDetail(arguments:arguments),
};//带参方法 注意 {arguments} 以及 页面参数 arguments:arguments
// 固定写法,统一处理,无需更改
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.class MyApp extends StatelessWidget中配置

import './routers/routes.dart';//引入刚配置的路由详情
child: MaterialApp(
 title: KString.mainTitle,//路由传参页面
 debugShowCheckedModeBanner: false,//
 home: IndexPages(),
  //配置命名路由
 initialRoute: '/', //初始化加载的路由
 onGenerateRoute: onGenerateRoute //刚刚routes中的方法

3.需要jump的页面

Navigator.pushNamed(context, '/goods/detail',arguments: {"goodsId":item['id']}); //{"goodsId":item['id']} 为参数内容

4.具体要跳转的页面

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import '../../service/http_service.dart';
import '../../config/index.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class GoodsDetail extends StatefulWidget {
  Map arguments;
  //将参数传递给子类~~~~
  GoodsDetail({Key key, this.arguments}) : super(key: key);
  _GoodsDetail createState() => _GoodsDetail();
}
class _GoodsDetail extends State<GoodsDetail> {
  @override
 void initState() {
    // TODO: implement initState
 super.initState();
    print('-----------');
    print(widget.arguments['goodsId']);//获得的参数内容
  }
  @override
 Widget build(BuildContext context) {
    // TODO: implement build
 return Scaffold(
        appBar: AppBar(
          title: Text(KString.goodsDetailTitleText),
        ),
        body: Row(
          children: <Widget>[
            Expanded(
                flex: 1,
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[Text('商品详情页面')])),
          ],
        ));
  }
}

刚学习flutter , 进行带参跳转时 没在routes中添加onGenerateRoute方法,而是在main函数中直接写routes路由参数,导致带参一直不成功,希望新入坑的童鞋不要在掉进来。

阅读 2.2k
34 声望
0 粉丝
0 条评论
34 声望
0 粉丝
文章目录
宣传栏