1.基礎(chǔ)用法
1.1最基本的使用-跳轉(zhuǎn)和退出
跳轉(zhuǎn):Navigator.push()
退出:Navigator.pop()
2.進(jìn)階用法:路由表
路由表:統(tǒng)一管理路由跳轉(zhuǎn)問題
使用方法:Navigator.pushNamed()
2.1用法
MaterialApp(
// 定義APP啟動(dòng)時(shí)第一個(gè)顯示的頁(yè)面
initialRoute: '/',
routes: {
//當(dāng)navigating到‘/’ route時(shí),構(gòu)建FirstScreen widget
'/': (context) => FirstScreen(),
//當(dāng)navigating 到"/second" route, 構(gòu)建SecondScreen widget.
'/second': (context) => SecondScreen(),
},
);
跳轉(zhuǎn)方法:
跳轉(zhuǎn): Navigator.pushNamed(context, '/second');
返回 :Navigator.pop(context);
3.頁(yè)面間值傳遞
Navigator.pushNamed()源碼
@optionalTypeArgs
static Future<T> pushNamed<T extends Object>(
BuildContext context,
//路由路徑
String routeName, {
//攜帶的參數(shù)
Object arguments,
}) {
return Navigator.of(context).pushNamed<T>(routeName, arguments: arguments);
}
arguments是跳轉(zhuǎn)攜帶的參數(shù),它是一個(gè)Object击孩,意味著可以傳遞任意類型的參數(shù)!
3.1 準(zhǔn)備傳遞的數(shù)據(jù)
多個(gè)數(shù)據(jù)時(shí)準(zhǔn)備一個(gè)bean配深,
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
3.2接受傳遞的數(shù)據(jù)
創(chuàng)建一個(gè)頁(yè)面來接受數(shù)據(jù)
class ExtractArgumentsScreen extends StatelessWidget {
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
//獲取傳遞的參數(shù)
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
通過 :ModalRoute.of(context).settings.arguments;獲取傳遞的參數(shù)
3.3谆趾,在MyApp里面注冊(cè)
MaterialApp(
routes: {
//或者 '/extractArguments' :(context) => ExtractArgumentsScreen(),
ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
},
);
3.4 跳轉(zhuǎn)頁(yè)面
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'我是被傳遞的title',
'我是被傳遞的message.',
)
或者
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ExtractArgumentsScreen(),
settings: RouteSettings(
arguments: ScreenArguments(
'我是title',
'我是message.',
),
) ,
),
);
4.攜帶參數(shù)退出
4.1跳轉(zhuǎn)頁(yè)面:
_push() async {
final result = await Navigator.push(
context,
// Create the SelectionScreen in the next step.
MaterialPageRoute(builder: (context) => SecondScreen()),
);
}
其中result就是我們要的返回值
4.2 返回頁(yè)面:
Navigator.pop(context, 'xxx!');
由于源碼中 pop的方法是Object,這里可以傳遞任意類型參數(shù)返回
@optionalTypeArgs
static void pop<T extends Object>(BuildContext context, [ T result ]) {
Navigator.of(context).pop<T>(result);
}
5.高級(jí)用法
PushAndRemove:跳轉(zhuǎn)到一個(gè)新的頁(yè)面并且銷毀當(dāng)前頁(yè)
popUntil:一直退出直到某一個(gè)頁(yè)面
pushReplacement:跳轉(zhuǎn)到下一頁(yè)的時(shí)候?qū)⒅八械捻?yè)面都銷毀叛本,先進(jìn)入再退出
popAndPushNamed:退出當(dāng)前頁(yè)面并且將新的頁(yè)面放到它原來的位置上沪蓬,先退出再進(jìn)入
maybePop:判斷依據(jù)就是看當(dāng)前路由是否處在棧中“最底部”的位置,如果不是就退出
canPop:返回一個(gè)bool值来候,表示當(dāng)前頁(yè)面是否可以退出
6第三方路由 FlutterBoost
FlutterBoosts是阿里閑魚團(tuán)隊(duì)開源的一款路由框架,新一代Flutter-Native混合解決方案跷叉。 FlutterBoost是一個(gè)Flutter插件,它可以輕松地為現(xiàn)有原生應(yīng)用程序提供Flutter混合集成方案营搅。FlutterBoost的理念是將Flutter像Webview那樣來使用云挟。在現(xiàn)有應(yīng)用程序中同時(shí)管理Native頁(yè)面和Flutter頁(yè)面并非易事。 FlutterBoost幫你處理頁(yè)面的映射和跳轉(zhuǎn)转质,你只需關(guān)心頁(yè)面的名字和參數(shù)即可
6.1 在Flutter項(xiàng)目中添加依賴項(xiàng)园欣。
在pubspec.yaml中添加依賴(注意:flutter_boost的版本要和本地的Flutter保持一致,或者使用穩(wěn)定的版本)
flutter_boost:
git:
url: 'https://github.com/alibaba/flutter_boost.git'
ref: '1.12.13+1'
在app目錄下的build.gradle中添加以下項(xiàng)目依賴
dependencies {
...
implementation project(':flutter_boost')
}
6.2 Flutter module項(xiàng)目使用FlutterBoost
main方法中運(yùn)行的rootWidget中注冊(cè)
@override
void initState() {
super.initState();
FlutterBoost.singleton.registerPageBuilders({
'flutterbus://flutterFirstPage': (pageName, params, _) {
...
return FirstPage();
},
'flutterbus://flutterSecondPage': (pageName, params, _) {
...
return SecondPage();
},
});
FlutterBoost.handleOnStartPage();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Boost example',
builder: FlutterBoost.init(),
home: Container());
}
6.3 原生配置
6.3.1 在MyApplication中初始化
INativeRouter router = new INativeRouter() {
@Override
public void openContainer(Context context, String url, Map<String, Object> urlParams, int requestCode, Map<String, Object> exts) {
String assembleUrl = Utils.assembleUrl(url, urlParams);
PageRouter.openPageByUrl(context, assembleUrl, urlParams);
}
};
FlutterBoost.BoostLifecycleListener boostLifecycleListener = new FlutterBoost.BoostLifecycleListener() {
@Override
public void beforeCreateEngine() {
}
@Override
public void onEngineCreated() {
// 注冊(cè)MethodChannel峭拘,監(jiān)聽flutter側(cè)的getPlatformVersion調(diào)用
MethodChannel methodChannel = new MethodChannel(FlutterBoost.instance().engineProvider().getDartExecutor(), "flutter_native_channel");
methodChannel.setMethodCallHandler((call, result) -> {
if (call.method.equals("getPlatformVersion")) {
result.success(Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
});
// 注冊(cè)PlatformView viewTypeId要和flutter中的viewType對(duì)應(yīng)
FlutterBoost
.instance()
.engineProvider()
.getPlatformViewsController()
.getRegistry()
.registerViewFactory("plugins.test/view", new TextPlatformViewFactory(StandardMessageCodec.INSTANCE));
}
@Override
public void onPluginsRegistered() {
}
@Override
public void onEngineDestroy() {
}
};
Platform platform = new FlutterBoost
.ConfigBuilder(this, router)
.isDebug(true)
.whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
.renderMode(FlutterView.RenderMode.texture)
.lifecycleListener(boostLifecycleListener)
.build();
FlutterBoost.instance().init(platform);
6.3.2 AndroidManifest.xml 配置
<activity
android:name="com.idlefish.flutterboost.containers.BoostFlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/ic_launcher_background" />
</activity>
6.4 原生頁(yè)面跳轉(zhuǎn)到Flutter
無(wú)參數(shù)跳轉(zhuǎn)
Intent intent = BoostFlutterActivity.withNewEngine().url("flutterSecondPage").params(null)
.backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(this);
startActivity(intent);
有參跳轉(zhuǎn)
Map map = new HashMap();
map.put("params1", "xx");
map.put("params2", xxx);
PageRouter.openPageByUrl(this, "first_page", map);
有參 + 返回值
Map map = new HashMap();
map.put("params1", "xx");
map.put("params2", xxx);
PageRouter.openPageByUrl(this, "second_page", map, 101);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && data.getExtras() != null) {
Toast.makeText(this, data.getExtras().get(IFlutterViewContainer.RESULT_KEY).toString(),
Toast.LENGTH_LONG).show();
}
}
6.5Flutter 之間跳轉(zhuǎn)
// 無(wú)參
FlutterBoost.singleton.open('second_page');
// 有參
FlutterBoost.singleton.open('second_page', urlParams: {'params1': 'xx', 'params2': xx});
// 有參 + 返回值
FlutterBoost.singleton.open('second_page', urlParams: { 'params1': 'xx', 'params2': xx })
.then((Map value) { print('Second Page 頁(yè)面銷毀時(shí)獲取的返回結(jié)果 result = $value'); });