flutter-Routers基础介绍

简介: flutter的路由管理与平时PC和app的工作原理一样,思路:知道使用流程和配置流程,进行配置和使用

  1. flutter-Routers基础介绍_第1张图片
    第一步:在pages/routers下有Routers.dart文件,当前文件属于router配置文件,这个几乎是固定写法,如果有新的路由页面,继续添加即可,代码如下
import 'package:flutter/material.dart';
import 'package:cai_customer/pages/Login/LoginPage.dart';
import '../pages/Tab.dart' as TabContainer;

final Map<String, Object> routes = {
  '/': (context) => TabContainer.Tab(),
  '/login': (context) => LoginPage(),
};

//固定写法
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;
    }
  }
};
  1. 第二步:注册router,在入口文件main.dart里面进行操作:flutter-Routers基础介绍_第2张图片
    关键代码:
 @override
  Widget build(BuildContext context) {
    ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
      return getErrorWidget(context, errorDetails);
    };
    return new MaterialApp(
      localeListResolutionCallback:
          (List<Locale> locales, Iterable<Locale> supportedLocales) {
        return Locale('zh');
      },
      localeResolutionCallback:
          (Locale locale, Iterable<Locale> supportedLocales) {
        return Locale('zh');
      },
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
      debugShowCheckedModeBanner: false,
      initialRoute: '/login', //默认进入login页面
      onGenerateRoute: onGenerateRoute,   //路由注册
      builder: EasyLoading.init(),
    );
  }
}

注意:main.dart注册的onGenerateRoute和routers里面定义的onGenerateRoute统一的。

  1. 第三步:router跳转
//下面 _toggleFavorite只是一个方法调用:
child: InkWell(
   onTap: () {
        _toggleFavorite();
      },
      child: Text("查看",
          style: TextStyle(
              color: Colors.orange,
              fontSize: 12)),
),
void _toggleFavorite() {
    Navigator.pushNamed(context, '/orderDetail', arguments: data);
  }

注意:arguments传参使用;routers.dart里面也对应了相应的参数配置

QQ技术交流群:707 196 135  (大前端技术交流群)

你可能感兴趣的:(Flutter,Dart,flutter)