【Flutter】路由封裝

又過了好久课竣,一直拖著沒有寫Flutter相關(guān)的東西了。已經(jīng)快忘記的差不多了置媳,最近實(shí)在是比較忙于樟,項(xiàng)目上線雌贱、一點(diǎn)空都沒有竟贯,不過最近好了一點(diǎn),本來一月份上線的項(xiàng)目最近延期了佳遂,一大堆的方案要寫寥袭。實(shí)在沒頭緒路捧,先不寫了,搞一下之前遺忘的條碼項(xiàng)目传黄。

這里記錄下杰扫,路由封裝的原理。
話不多說 直接上源碼膘掰,我們現(xiàn)在看下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<T> extends PageRoute<T> {
  /// 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<dynamic> 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<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    final Widget result = builder(context);
    assert(() {
      if (result == null) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          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<double> animation, Animation<double> secondaryAnimation, Widget child) {
    final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme;
    return theme.buildTransitions<T>(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 {
  //路由設(shè)置

   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(),
  };

   //監(jiān)聽route,類似于攔截器原理
  Function getRoutes = (RouteSettings settings){

    print(settings);  //驗(yàn)證是否有效
    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

目前沒有帶參數(shù)惭聂,null是空窗声,表示沒有傳遞參數(shù)進(jìn)來。

main入口辜纲,直接調(diào)用路由函數(shù)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,
    );
  }
}

另外,這里的顯示還是有點(diǎn)問題耕腾,需要單獨(dú)處理一下见剩。將首頁的顯示進(jìn)行一個(gè)封裝。這樣是無法直接進(jìn)入到每個(gè)頁面扫俺。有空在處理一下苍苞。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狼纬,隨后出現(xiàn)的幾起案子羹呵,更是在濱河造成了極大的恐慌,老刑警劉巖疗琉,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件冈欢,死亡現(xiàn)場離奇詭異,居然都是意外死亡盈简,警方通過查閱死者的電腦和手機(jī)凑耻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來柠贤,“玉大人香浩,你說我怎么就攤上這事≈治” “怎么了弃衍?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長坚俗。 經(jīng)常有香客問我镜盯,道長,這世上最難降的妖魔是什么猖败? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任速缆,我火速辦了婚禮,結(jié)果婚禮上恩闻,老公的妹妹穿的比我還像新娘艺糜。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布破停。 她就那樣靜靜地躺著翅楼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪真慢。 梳的紋絲不亂的頭發(fā)上毅臊,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機(jī)與錄音黑界,去河邊找鬼管嬉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛朗鸠,可吹牛的內(nèi)容都是我干的蚯撩。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼烛占,長吁一口氣:“原來是場噩夢啊……” “哼胎挎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起扰楼,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤呀癣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后弦赖,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體项栏,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年蹬竖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了沼沈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡币厕,死狀恐怖列另,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情旦装,我是刑警寧澤页衙,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站阴绢,受9級特大地震影響店乐,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜呻袭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一眨八、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧左电,春花似錦廉侧、人聲如沸页响。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽闰蚕。三九已至,卻和暖如春枕扫,著一層夾襖步出監(jiān)牢的瞬間陪腌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工烟瞧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人染簇。 一個(gè)月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓参滴,卻偏偏與公主長得像,于是被迫代替她去往敵國和親锻弓。 傳聞我的和親對象是個(gè)殘疾皇子砾赔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355