相关使用可以参考网上,这里不在阐述,说下遇到的一个文件,就是flutter页面调原生方法关闭时,flutter页面没有走dispose方法。
解决办法:
1、调原生方法关闭时,先执行下flutter的路由关闭
Navigator.pop(context);
2、flutter MyAppWIdget 中定义一个变量isDetached, build方法里面,根据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:
// 相关处理参考
// https://github.com/flutter/flutter/pull/137957
runApp(const MyApp(isDetached: true));
// 清除内存中的图片缓存
// 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, 以此来及时释放资源
Widget resultWidget = const SizedBox.shrink();
// Fix report no OKToast widget found.
// resultWidget = OKToast(child: resultWidget);
return resultWidget;
}
return MaterialApp(
...
);
}
}