flutter开发实战-第一帧布局完成回调实现

flutter开发实战-第一帧布局完成回调实现

在开发中,我们有时候需要在第一帧布局完成后调用一些相关的方法。这里记录一下是实现过程。

Flutter中有多种不同的Binding,每种Binding都负责不同的功能。下面是Flutter中常见的Binding:

这里简单说明一下WidgetsBinding

一、WidgetsBinding

WidgetsBinding:负责管理Flutter应用程序的生命周期,包括启动、暂停、恢复和停止等。

WidgetsBinding它用于监听用户设置的更改,如语言的修改。 不仅如此, WidgetsBinding 否是 Widgets 与 Flutter 引擎之间通信的桥梁,有两个主要的功能:

* 1 负责处理Widgets结构变更的过程;

* 2 第二个是触发渲染事件。

一些小组件的结构更改是 BuildOwner 来完成的,它跟踪需要重建的小部件,并处理应用于整个小部件结构的其他任务。

二、实现第一帧布局完成后调用相关方法

在WidgetsBinding中,我们可以看到endOfFrame方法,源码如下

复制代码
/// Returns a Future that completes after the frame completes.
  ///
  /// If this is called between frames, a frame is immediately scheduled if
  /// necessary. If this is called during a frame, the Future completes after
  /// the current frame.
  ///
  /// If the device's screen is currently turned off, this may wait a very long
  /// time, since frames are not scheduled while the device's screen is turned
  /// off.
  Future<void> get endOfFrame {
    if (_nextFrameCompleter == null) {
      if (schedulerPhase == SchedulerPhase.idle) {
        scheduleFrame();
      }
      _nextFrameCompleter = Completer<void>();
      addPostFrameCallback((Duration timeStamp) {
        _nextFrameCompleter!.complete();
        _nextFrameCompleter = null;
      });
    }
    return _nextFrameCompleter!.future;
  }

方法中描述如下

复制代码
该方法返回在帧完成后完成的Future。
如果在帧之前调用的时候,则会立即调度帧。如果在帧期间调用此操作,则Future将在当前帧完成后调用。
如果设备的屏幕当前已关闭,这可能会等待很长时间。

所以我们需要在initState中调用相关方法

复制代码
WidgetsBinding.instance.endOfFrame.then(
          (value) {
        if (mounted) {
           // TODO调用相关方法
        }
      },
    );

实现第一帧布局完成后调用完成代码如下

复制代码
class AfterLayoutPage extends StatefulWidget {
  const AfterLayoutPage({super.key});

  @override
  State<AfterLayoutPage> createState() => _AfterLayoutPageState();
}

class _AfterLayoutPageState extends State<AfterLayoutPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AfterLayoutPage'),
      ),
      body: Container(
        color: Colors.blueGrey,
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.endOfFrame.then(
          (value) {
        if (mounted) {
          showHelloWorld();
        }
      },
    );
  }

  void showHelloWorld() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: const Text('Hello World'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('DISMISS'),
            )
          ],
        );
      },
    );
  }
}

可以将该实现包装成一个Mixin

复制代码
import 'dart:async';

import 'package:flutter/widgets.dart';

mixin AfterLayoutMixin<T extends StatefulWidget> on State<T> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.endOfFrame.then(
      (_) {
        if (mounted) afterFirstLayout(context);
      },
    );
  }

  FutureOr<void> afterFirstLayout(BuildContext context);
}

调整后代码如下

复制代码
class AfterLayoutPage extends StatefulWidget {
  const AfterLayoutPage({super.key});

  @override
  State<AfterLayoutPage> createState() => _AfterLayoutPageState();
}

class _AfterLayoutPageState extends State<AfterLayoutPage> with AfterLayoutMixin<AfterLayoutPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AfterLayoutPage'),
      ),
      body: Container(
        color: Colors.blueGrey,
      ),
    );
  }

  @override
  void afterFirstLayout(BuildContext context) {
    // Calling the same function "after layout" to resolve the issue.
    showHelloWorld();
  }

  void showHelloWorld() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: const Text('Hello World'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('DISMISS'),
            )
          ],
        );
      },
    );
  }
}

三、小结

flutter开发实战-第一帧布局完成回调实现

学习记录,每天不停进步。

相关推荐
遇到困难睡大觉哈哈3 小时前
Harmony os——ArkTS 高性能编程实践 – 速查笔记
笔记·harmonyos·鸿蒙
iiiiii113 小时前
【论文阅读笔记】IDAQ:离线元强化学习中的分布内在线适应
论文阅读·人工智能·笔记·学习·算法·机器学习·强化学习
用户7502734994773 小时前
我用百度文心快码开发了一款积木工坊:用AI让每个孩子都成为小小建筑师
flutter
点亮一颗LED(从入门到放弃)3 小时前
C语言学习笔记(1)——输入输出,数据类型
c语言·笔记·学习
土拨鼠烧电路3 小时前
RPA悖论迷思:从解放的利器到运维的枷锁?
大数据·运维·笔记·rpa
IMPYLH3 小时前
Lua 的 select 函数
java·开发语言·笔记·后端·junit·游戏引擎·lua
云半S一3 小时前
春招准备之测试基础理论篇
经验分享·笔记·功能测试·测试覆盖率
摇滚侠3 小时前
2025最新 SpringCloud 教程,Nacos-注册中心-服务发现功能,笔记07
笔记·spring cloud·服务发现
CoderYanger4 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:13.子集
java·算法·leetcode·机器学习·剪枝·1024程序员节
名字被你们想完了4 小时前
Flutter 实现一个容器内部元素可平移、缩放和旋转等功能(一)
flutter