【Flutter】路由封装

又过了好久,一直拖着没有写Flutter相关的东西了。已经快忘记的差不多了,最近实在是比较忙,项目上线、一点空都没有,不过最近好了一点,本来一月份上线的项目最近延期了,一大堆的方案要写。实在没头绪,先不写了,搞一下之前遗忘的条码项目。

这里记录下,路由封装的原理。
话不多说 直接上源码,我们现在看下flutter中的源码是怎么写的?

核心看MaterialPageRoute 方法

// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';

import 'page_transitions_theme.dart';
import 'theme.dart';

/// A modal route that replaces the entire screen with a platform-adaptive
/// transition.
///
/// For Android, the entrance transition for the page slides the page upwards
/// and fades it in. The exit transition is the same, but in reverse.
///
/// The transition is adaptive to the platform and on iOS, the page slides in
/// from the right and exits in reverse. The page also shifts to the left in
/// parallax when another page enters to cover it. (These directions are flipped
/// in environments with a right-to-left reading direction.)
///
/// By default, when a modal route is replaced by another, the previous route
/// remains in memory. To free all the resources when this is not necessary, set
/// [maintainState] to false.
///
/// The `fullscreenDialog` property specifies whether the incoming page is a
/// fullscreen modal dialog. On iOS, those pages animate from the bottom to the
/// top rather than horizontally.
///
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.pop] by providing the
/// optional `result` argument.
///
/// See also:
///
///  * [PageTransitionsTheme], which defines the default page transitions used
///    by [MaterialPageRoute.buildTransitions].
class MaterialPageRoute extends PageRoute {
  /// Construct a MaterialPageRoute whose contents are defined by [builder].
  ///
  /// The values of [builder], [maintainState], and [fullScreenDialog] must not
  /// be null.
  MaterialPageRoute({
    @required this.builder,
    RouteSettings settings,
    this.maintainState = true,
    bool fullscreenDialog = false,
  }) : assert(builder != null),
       assert(maintainState != null),
       assert(fullscreenDialog != null),
       assert(opaque),
       super(settings: settings, fullscreenDialog: fullscreenDialog);

  /// Builds the primary contents of the route.
  final WidgetBuilder builder;

  @override
  final bool maintainState;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  Color get barrierColor => null;

  @override
  String get barrierLabel => null;

  @override
  bool canTransitionTo(TransitionRoute nextRoute) {
    // Don't perform outgoing animation if the next route is a fullscreen dialog.
    return (nextRoute is MaterialPageRoute && !nextRoute.fullscreenDialog)
        || (nextRoute is CupertinoPageRoute && !nextRoute.fullscreenDialog);
  }

  @override
  Widget buildPage(
    BuildContext context,
    Animation animation,
    Animation secondaryAnimation,
  ) {
    final Widget result = builder(context);
    assert(() {
      if (result == null) {
        throw FlutterError.fromParts([
          ErrorSummary('The builder for route "${settings.name}" returned null.'),
          ErrorDescription('Route builders must never return null.')
        ]);
      }
      return true;
    }());
    return Semantics(
      scopesRoute: true,
      explicitChildNodes: true,
      child: result,
    );
  }

  @override
  Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) {
    final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme;
    return theme.buildTransitions(this, context, animation, secondaryAnimation, child);
  }

  @override
  String get debugLabel => '${super.debugLabel}(${settings.name})';
}

builder 不能为空,builder是什么?我们来找一下。这里定义的builder可以理解为是一种BuildContext

  /// Builds the primary contents of the route.
  final WidgetBuilder builder;

typedef WidgetBuilder = Widget Function(BuildContext context);

/// Signature for a function that creates a widget for a given index, e.g., in a
/// list.
///
/// Used by [ListView.builder] and other APIs that use lazily-generated widgets.
///
/// See also:
///
///  * [WidgetBuilder], which is similar but only takes a [BuildContext].
///  * [TransitionBuilder], which is similar but also takes a child.


/**
 * @Author: zhouge
 * @Description: 路由
 * @Date: Created in 19:38 2021-01-02
 * @Modified By:
 **/

import 'package:SmartCode/Pages/login/LoginPage.dart';
import 'package:SmartCode/Pages/Purchasepage.dart';
import 'package:SmartCode/Pages/Salespage.dart';
import 'package:SmartCode/Pages/WareHousePage.dart';
import 'package:SmartCode/Pages/Workpage.dart';
import 'package:flutter/material.dart';
import 'package:SmartCode/Pages/Settingpage.dart';
import 'package:SmartCode/Homepage.dart';

class Router {
  //路由设置

   static final _routes = {
    "/": (context,{Object args}) => LoginPages(),
    '/settings': (context,{Object args}) => SettingPages(),
    '/purchase': (context,{Object args}) => PurchasePages(),
    '/sales': (context,{Object args}) => SalesPages(),
    '/warehouse': (context,{Object args}) => WareHousePages(),
    '/work': (context,{Object args}) => WorkPages(),
    '/home': (context,{Object args}) => HomePages(),
  };

   //监听route,类似于拦截器原理
  Function getRoutes = (RouteSettings settings){

    print(settings);  //验证是否有效
    final routeName = settings.name;
    final Function builder = _routes[routeName];
    Route route;

    if (builder == null){
      return route;
    }else{
      route = MaterialPageRoute(builder:(context) => builder(context,args:settings.arguments));
    }
    return route;
  };
}

打印信息查看

image.png

目前没有带参数,null是空,表示没有传递参数进来。

main入口,直接调用路由函数getRoutes获取。


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:SmartCode/routes/routes.dart';

//初始化路由
final Router router = Router();

void main() => runApp(MyApp());

final String SUPPLIER_URL = 'http://192.168.0.12';
final String SMART_URL = 'http://192.168.0.13/ws/web/r/awsp900';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      onGenerateRoute:router.getRoutes,
    );
  }
}

另外,这里的显示还是有点问题,需要单独处理一下。将首页的显示进行一个封装。这样是无法直接进入到每个页面。有空在处理一下。

你可能感兴趣的:(【Flutter】路由封装)