Flutter - UIKit开发相关指南 - 控制器,主题,表单

环境

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值