相關(guān)使用可以參考網(wǎng)上,這里不在闡述,說下遇到的一個(gè)文件,就是flutter頁(yè)面調(diào)原生方法關(guān)閉時(shí),flutter頁(yè)面沒有走dispose方法。
解決辦法:
1、調(diào)原生方法關(guān)閉時(shí),先執(zhí)行下flutter的路由關(guān)閉
Navigator.pop(context);
2、flutter MyAppWIdget 中定義一個(gè)變量isDetached, build方法里面,根據(jù)isDetached返回特定widget
main(List<String> args) async {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
final bool isDetached;
const MyApp({
Key? key,
this.isDetached = false,
}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.detached:
// 相關(guān)處理參考
// https://github.com/flutter/flutter/pull/137957
runApp(const MyApp(isDetached: true));
// 清除內(nèi)存中的圖片緩存
// https://github.com/Baseflow/flutter_cached_network_image/issues/429
final imageCache = PaintingBinding.instance.imageCache;
imageCache.clear();
imageCache.clearLiveImages();
break;
default:
}
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
if (widget.isDetached) {
// 引擎被detach, 移除所有的widget, 以此來及時(shí)釋放資源
Widget resultWidget = const SizedBox.shrink();
// Fix report no OKToast widget found.
// resultWidget = OKToast(child: resultWidget);
return resultWidget;
}
return MaterialApp(
...
);
}
}