环境
Flutter 3.29
macOS Sequoia 15.4.1
Xcode 16.3
控制器(ViewControllers)
在UIKit中,通过ViewController控制数据在视图上展现,多个ViewController组合在一起构建复杂的用户界面。在Flutter中,因为所有都是Widget,所以ViewController相关的功能也由Widget来承担。
生命周期事件
在UIKit中可以重写自定义控制器的生命周期的方法,或注册AppDelegate的回调。在Flutter3.13前,没有这个概念,但是可以通过监听WidgetsBinding观察者和didChangeAppLifecycleState()改变事件来实现
import 'package:flutter/material.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({
super.key});
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: Center(child: BindingObserver())),
);
}
}
class BindingObserver extends StatefulWidget {
const BindingObserver({
super.key});
State<BindingObserver> createState() => _BindingObserverState();
}
class _BindingObserverState extends State<BindingObserver>
with WidgetsBindingObserver {
void initState() {
super.initState();
// 1.添加App事件变化的观察者
WidgetsBinding.instance.addObserver(this);
}
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
// 2.监听app生命周期变化的事件
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.detached:
_onDetached();
/// On all platforms, this state indicates that the application is in the default running mode for a running application that has input focus and is visible.
/// 应用可见且能响应用户的输入,切回前台会触发
case AppLifecycleState.resumed:
_onResumed();
/// At least one view of the application is visible, but none have input focus. The application is otherwise running normally.
/// 应用程序处于非活跃状态,并且未接收用户输入。此事件仅适用于 iOS,因为 Android 上没有对应的事件。
/// 切到后台先触发这个方法
case AppLifecycleState.inactive:
_onInactive();
/// All views of an application are hidden, either because the application is about to be paused (on iOS and Android), or because it has been minimized or placed on a desktop that is no longer visible (on non-web desktop), or is running in a window or tab that is no longer visible (on the web).
/// 所有的应用视图被隐藏,或者应用被暂停
case AppLifecycleState.hidden:
_onHidden();
/// The application is not currently visible to the user, and not responding to user input.
/// When the application is in this state, the engine will not call the [PlatformDispatcher.onBeginFrame] and [PlatformDispatcher.onDrawFrame] callbacks.
/// This state is only entered on iOS and Andr

最低0.47元/天 解锁文章
1559

被折叠的 条评论
为什么被折叠?



