背景
經(jīng)常性的久又,我們需要監(jiān)視頁面的切換,用以在合適的時(shí)候?qū)丶M(jìn)行動(dòng)畫暫托澹或者資源釋放地消。
舉個(gè)栗子:
相機(jī)拍照是我們需要經(jīng)常用到的功能,但是當(dāng)我們?cè)谇袚Q到相機(jī)配置頁面時(shí)火俄,需要暫停當(dāng)前相機(jī)預(yù)覽犯建,這種情況下我們就需要監(jiān)視頁面的路由變化情況,又或者用戶回到應(yīng)用桌面瓜客,此時(shí)也需要對(duì)相機(jī)進(jìn)行暫停适瓦,返回又恢復(fù)相機(jī)。
在這里主要關(guān)系到下面兩個(gè)方面的:
- AppStateLifeRecycle - 今天我們不說這個(gè)谱仪;
- RouteAware
先看看RouteAware是如何定義的玻熙?
/// An interface for objects that are aware of their current [Route].
///
/// This is used with [RouteObserver] to make a widget aware of changes to the
/// [Navigator]'s session history.
abstract class RouteAware {
/// Called when the top route has been popped off, and the current route
/// shows up.
void didPopNext() { }
/// Called when the current route has been pushed.
void didPush() { }
/// Called when the current route has been popped off.
void didPop() { }
/// Called when a new route has been pushed, and the current route is no
/// longer visible.
void didPushNext() { }
}
上面提交到4個(gè)方法,分別都有什么用呢疯攒?
假如有3個(gè)頁面嗦随,分別是A、B敬尺、C枚尼,跳轉(zhuǎn)邏輯由A->B->C,而RouteAware使用with混淆在B中砂吞。
- didPopNext:在C頁面關(guān)閉后署恍,B頁面調(diào)起該方法;
- didPush: 當(dāng)由A打開B頁面時(shí)蜻直,B頁面調(diào)起該方法盯质;
- didPop: 當(dāng)B頁面關(guān)閉時(shí)袁串,B頁面調(diào)起該方法;
- didPushNext: 當(dāng)從B頁面打開C頁面時(shí)呼巷,該方法被調(diào)起囱修。
如何使用?
- 使用with關(guān)鍵字在State類中使用王悍,使用前在MaterialApp中定義一個(gè)RouteObserver對(duì)象破镰。
如下:
final RouteObserver<Route<dynamic>> routeObserver = RouteObserver();
class MyApp extends StatelessWidget {
... \\此處省略一些代碼
Widget _buildMaterialApp() => MaterialApp(
initialRoute: '/',
navigatorObservers: [routeObserver], //添加路由觀察者
onGenerateRoute: _onGenerateRoute);
}
- 在B頁面中混淆RouteAware, 并注冊(cè)RouteObserver
如下:
class B extends StatefulWidget {
B({Key key}) : super(key: key);
}
class BState extends State<B> with RouteAware {
@override
void didChangeDependencies() {
routeObserver.subscribe(this, ModalRoute.of(context)); //訂閱
super.didChangeDependencies();
}
@override
void didPush() {
debugPrint("------> didPush");
super.didPush();
}
@override
void didPop() {
debugPrint("------> didPop");
super.didPop();
}
@override
void didPopNext() {
debugPrint("------> didPopNext");
super.didPopNext();
}
@override
void didPushNext() {
debugPrint("------> didPushNext");
super.didPushNext();
}
@override
void dispose() {
routeObserver.unsubscribe(this); //取消訂閱
super.dispose();
}
}
總結(jié) :-)
- 路由觀察者添加訂閱與取消訂閱必須成對(duì)出現(xiàn);
- 一些對(duì)象在使用后一定要記得及時(shí)釋放資源配名。
其他:轉(zhuǎn)載請(qǐng)注明出處啤咽,謝謝!