Flutter路由之fluro的配置及跳轉

1、pubspec.yaml導包,註意格式~

dependencies:
  flutter:
    sdk: flutter
  fluro: ^1.6.3

2、新建路由類,改類是定義頁面的路徑,然後將頁面handler和路徑設置到路由中

class Routers {
  static Router router;
  //文件夾須跟main.dart目錄同級
  static String root = '/';
  static String loginPage = '/loginPage';
  static String tabsPage = '/tabsPage';
  static String messageDetailPage = '/messageDetailPage';
  static String serviceSettingPage = '/serviceSettingPage';

  static void configureRoutes(Router router) {
    router.notFoundHandler = Handler(
        handlerFunc: (BuildContext context, Map<String, List<String>> params) {
      print("ROUTE WAS NOT FOUND !!!");
      return null;
    });
    router.define(loginPage, handler: loginHandler);
    router.define(messageDetailPage, handler: messageDetailHandler);
    router.define(tabsPage, handler: tabsHandler);
    router.define(serviceSettingPage, handler: serviceSettingHandler);
  }

  // 對參數進行encode,解決參數中有特殊字符,影響fluro路由匹配,尤其中文
  static Future navigateTo(BuildContext context, String path,
      {Map<String, dynamic> params,
      TransitionType transition = TransitionType.inFromRight,
      bool replace = false}) {
    String query = "";
    if (params != null) {
      int index = 0;
      for (var key in params.keys) {
        var value = Uri.encodeComponent(params[key]);
        if (index == 0) {
          query = "?";
        } else {
          query = query + "\&";
        }
        query += "$key=$value";
        index++;
      }
    }
    print('我是navigateTo傳遞的參數:$query');

    path = path + query;
    return router.navigateTo(context, path,
        transition: transition, replace: replace);
  }

  static void finishAllToLoginPage() {
    //跳轉指定頁面並關閉當前所有頁面
    //關閉所有頁面時會導致tabs_page頁面先執行initState,再執行dispose,導致無法再監聽,所以要註意
    Global.navKey.currentState.pushAndRemoveUntil(
        new MaterialPageRoute(builder: (context) => new LoginPage()),
        (route) => route == null);//會執行所有頁面的dispose
  }
}

3、新建router_handler.dart,處理參數和跳轉頁面

//登錄
var loginHandler = new Handler(
    handlerFunc: (BuildContext context, Map<String, List<String>> params) {
  return new LoginPage();
});

//消息詳情頁
var messageDetailHandler = new Handler(
    handlerFunc: (BuildContext context, Map<String, dynamic> params) {
  //取參
  String barTitle = params["bar_title"]?.first;
  String itemDataJson = params["item_data"]?.first;
  return new MessageDetailPage(
    barTitle: barTitle,
    itemDataJson: itemDataJson,
  );
});

//主頁Tabs
var tabsHandler = new Handler(
    handlerFunc: (BuildContext context, Map<String, List<String>> params) {
  return new TabsPage();
});

//Service setting
var serviceSettingHandler = new Handler(
    handlerFunc: (BuildContext context, Map<String, List<String>> params) {
  return new ServiceSettingPage();
});

4、調用傳參

 //對象需要轉String
                      String itemDataJson = FluroConvertUtils.object2string(
                          _bulletinsList[index]);
                      Routers.navigateTo(context, Routers.messageDetailPage,
                          params: {
                            'bar_title': "Detail",
                            'item_data': itemDataJson,
                          });

5、接收數據

 //String轉回對象
    Bulletins itemData =
        Bulletins.fromJson(FluroConvertUtils.string2map(itemDataJson));

6、問題來瞭,因為fluro無法直接傳中文的,這裡就需要用到編碼碼解碼瞭,也就是encode和decode

class FluroConvertUtils {
  /// fluro 傳遞中文參數前,先轉換,fluro 不支持中文傳遞
  static String fluroCnParamsEncode(String originalCn) {
    return jsonEncode(Utf8Encoder().convert(originalCn));
  }

  /// fluro 傳遞後取出參數,解析
  static String fluroCnParamsDecode(String encodeCn) {
    var list = List<int>();

    ///字符串解碼
    jsonDecode(encodeCn).forEach(list.add);
    String value = Utf8Decoder().convert(list);
    return value;
  }

  /// string 轉為 int
  static int string2int(String str) {
    return int.parse(str);
  }

  /// string 轉為 double
  static double string2double(String str) {
    return double.parse(str);
  }

  /// string 轉為 bool
  static bool string2bool(String str) {
    if (str == 'true') {
      return true;
    } else {
      return false;
    }
  }

  /// object 轉為 string json
  static String object2string<T>(T t) {
    return fluroCnParamsEncode(jsonEncode(t));
  }

  /// string json 轉為 map
  static Map<String, dynamic> string2map(String str) {
    return json.decode(fluroCnParamsDecode(str));
  }
}

完美解決,這也是fluro使用的整個流程,基本小封裝瞭下,還有就是Routers需要在main.dart裡初始化:

 MyApp() {
    // 註冊初始化fluro
    final router = Router();
    Routers.configureRoutes(router);
    Routers.router = router;
  }

到此這篇關於Flutter 路由之fluro的具體使用的文章就介紹到這瞭,更多相關Flutter fluro內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: