Flutter键盘遮挡输入框问题

2023-11-06

以下代码是在网上看到的,忘记具体的出处了,请谅解

/**
 * 作者:Created by H on 2019/1/23 11:08.
 * 介绍: 解决输入框被遮挡问题
 */
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

///
/// Helper class that ensures a Widget is visible when it has the focus
/// For example, for a TextFormField when the keyboard is displayed
///
/// How to use it:
///
/// In the class that implements the Form,
///   Instantiate a FocusNode
///   FocusNode _focusNode = new FocusNode();
///
/// In the build(BuildContext context), wrap the TextFormField as follows:
///
///   new EnsureVisibleWhenFocused(
///     focusNode: _focusNode,
///     child: new TextFormField(
///       ...
///       focusNode: _focusNode,
///     ),
///   ),
///
/// Initial source code written by Collin Jackson.
/// Extended (see highlighting) to cover the case when the keyboard is dismissed and the
/// user clicks the TextFormField/TextField which still has the focus.
///
class EnsureVisibleWhenFocused extends StatefulWidget {
  const EnsureVisibleWhenFocused({
    Key key,
    @required this.child,
    @required this.focusNode,
    this.curve: Curves.ease,
    this.duration: const Duration(milliseconds: 100),
  }) : super(key: key);

  /// The node we will monitor to determine if the child is focused
  final FocusNode focusNode;

  /// The child widget that we are wrapping
  final Widget child;

  /// The curve we will use to scroll ourselves into view.
  ///
  /// Defaults to Curves.ease.
  final Curve curve;

  /// The duration we will use to scroll ourselves into view
  ///
  /// Defaults to 100 milliseconds.
  final Duration duration;

  @override
  _EnsureVisibleWhenFocusedState createState() => new _EnsureVisibleWhenFocusedState();
}

///
/// We implement the WidgetsBindingObserver to be notified of any change to the window metrics
///
class _EnsureVisibleWhenFocusedState extends State<EnsureVisibleWhenFocused> with WidgetsBindingObserver  {

  @override
  void initState(){
    super.initState();
    widget.focusNode.addListener(_ensureVisible);
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose(){
    WidgetsBinding.instance.removeObserver(this);
    widget.focusNode.removeListener(_ensureVisible);
    super.dispose();
  }

  ///
  /// This routine is invoked when the window metrics have changed.
  /// This happens when the keyboard is open or dismissed, among others.
  /// It is the opportunity to check if the field has the focus
  /// and to ensure it is fully visible in the viewport when
  /// the keyboard is displayed
  ///
  @override
  void didChangeMetrics(){
    if (widget.focusNode.hasFocus){
      _ensureVisible();
    }
  }

  ///
  /// This routine waits for the keyboard to come into view.
  /// In order to prevent some issues if the Widget is dismissed in the
  /// middle of the loop, we need to check the "mounted" property
  ///
  /// This method was suggested by Peter Yuen (see discussion).
  ///
  Future<Null> _keyboardToggled() async {
    if (mounted){
      EdgeInsets edgeInsets = MediaQuery.of(context).viewInsets;
      while (mounted && MediaQuery.of(context).viewInsets == edgeInsets) {
        await new Future.delayed(const Duration(milliseconds: 10));
      }
    }

    return;
  }

  Future<Null> _ensureVisible() async {
    // Wait for the keyboard to come into view
    await Future.any([new Future.delayed(const Duration(milliseconds: 300)), _keyboardToggled()]);

    // No need to go any further if the node has not the focus
    if (!widget.focusNode.hasFocus){
      return;
    }

    // Find the object which has the focus
    final RenderObject object = context.findRenderObject();
    final RenderAbstractViewport viewport = RenderAbstractViewport.of(object);
    assert(viewport != null);

    // Get the Scrollable state (in order to retrieve its offset)
    ScrollableState scrollableState = Scrollable.of(context);
    assert(scrollableState != null);

    // Get its offset
    ScrollPosition position = scrollableState.position;
    double alignment;

    if (position.pixels > viewport.getOffsetToReveal(object, 0.0).offset) {
      // Move down to the top of the viewport
      alignment = 0.0;
    } else if (position.pixels < viewport.getOffsetToReveal(object, 1.0).offset){
      // Move up to the bottom of the viewport
      alignment = 1.0;
    } else {
      // No scrolling is necessary to reveal the child
      return;
    }

    position.ensureVisible(
      object,
      alignment: alignment,
      duration: widget.duration,
      curve: widget.curve,
    );
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

引用方式如下:

FocusNode _focusNode = new FocusNode();
   new EnsureVisibleWhenFocused(
     focusNode: _focusNode,
     child: new TextFormField(
       ...
       focusNode: _focusNode,
    ),
   ),
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter键盘遮挡输入框问题 的相关文章

随机推荐

  • 基于FiscoBcos v3.0.1 pro版的host网络模式集群环境搭建

    安装软件 更新 最新版本系统软件 yum update y 安装docker yum install y yum utils device mapper persistent data lvm2 设置yum源 yum config mana
  • python+unittest+HTMLReopertRunner生成测试报告

    1 安装HTMLReport 在线安装 使用pip命令安装HTMLReport 命令 pip install HTMLReport 安装好的位置在 Python安装路径下的Lib site packages下 离线安装 直接将下载好的HTM
  • 现在上车音视频开发还来得及吗?论音视频开发的的前景趋势!

    一 行业现状 核心竞争力 定义音视频是程序届的皇冠 掌握音视频意味着拿到通往未来的船票 不用担心会被其他人替代 音视频是有门槛的 是与其他人拉开差距的分水岭 高端人才相关缺乏 Boss直聘中 北上广深很多年限上50w 70w的音视频岗位 常
  • Sqlilabs-22

    这里来到了第一阶段的最后一关 22 关 其实跟 21 关一样 只不过变成了双引号 而已 直接上菜吧o uname YWRtaW4iIGFuZCBleHRyYWN0dmFsdWUoMSxjb25jYXQoMHg3ZSwoc2VsZWN0IGR
  • 数字后端学习之SDC

    SDC是一个设计中最重要的文件 为什么这么说呢 ppa大家知道把 sdc就是要对ppa进行约束 那sdc有哪些具体的内容呢 1 描述芯片的工作速度 包括 create clock create generate clock 要知道clock
  • 华为OD机试 Python 称砝码

    题目 你有一些不同的砝码 每个砝码都有自己的重量和数量 试问 用这些砝码 你可以得到多少种不同的重量组合 输入 第一行给出砝码的种类数 n 1 n 10 第二行按顺序列出每种砝码的重量 重量范围为 1 m 2000 第三行按顺序列出每种砝码
  • 商品推荐(内容过滤 + 协同过滤)

    目录 1 名词列表 2 协同过滤 2 1 基于物品的协同过滤 itemCF 2 1 1 数据模型 2 1 2 商品相似度矩阵生成 2 1 3 推荐策略 2 2 基于用户的协同过滤 userCF 2 2 1 数据模型 2 2 2 用户相似度矩
  • Hive/MaxCompute SQL性能优化(三):数据倾斜优化实战

    SQL性能优化系列 Hive MaxCompute SQL性能优化 一 什么是数据倾斜 Hive MaxCompute SQL性能优化 二 如何定位数据倾斜 前面介绍了如何定位数据倾斜 本文介绍如果遇到各种数据倾斜的情况该怎样优化代码 Ma
  • LINUX基础试题大全(3)

    说明 此文章由于题数庞大 为方便阅读本人将其分为四篇文章为大家分享 答案会今后不断进行更新 LINUX基础试题大全 1 填空题题 LINUX基础试题大全 2 单项选择题 LINUX基础试题大全 3 简答 LINUX基础试题大全 4 数据结构
  • C语言指针数组和数组指针[转]

    ps 文章属于总结性前 第一部分部分来自于 http www cnblogs com hongcha717 archive 2010 10 24 1859780 html 数组指针 也称行指针 定义 int p n 优先级高 首先说明p是一
  • 车载通信——J1939故障码

    一 诊断 UDS是统一诊断系统 冻结帧 出现故障码时 ECU存储故障码出现时的数据 就是冻结帧 二 J1939故障诊断 SAE J1939应用层定义了12种诊断报文 Diagnostic Message DM 诊断故障码 DTC 故障码 可
  • eval(function(p,a,c,k,e,d) javascrip类型代码 解决办法

    eval function p a c k e d e function c return c35 String fromCharCode c 29 c toString 36 if replace String while c d e c
  • 均衡器--时域均衡,频域均衡,无限长迫零(Zero force\ZF)均衡器,有限长时域迫零(ZF)均衡器,无限长MSE均衡器

    均衡器 1 原因 2 线性均衡器 2 1时域均衡 2 2频域均衡 3 均衡器 3 1无限长迫零 Zero force ZF 均衡器 3 2有限长时域迫零 ZF 均衡器 3 3无限长MSE均衡器 4 性能比较 1 原因 之前讨论的是在AWGN
  • 【GitHubShare】适合练习python的编程类网站,可以边学边玩

    非常有意思的编程网站 leetcode pythontip Coding Games Codewars CodeCombat Checkio Cyber Dojo pythonchallenge Code Monkey leetcode l
  • 【Docker】Docker中启动redis

    1 使用命令 docker pull redis 来下载redis镜像 2 通过命令 docker images来查看redis镜像是否安装成功 3 安装成功后通过 docker run name java redis d redis 来运
  • 客户异常数据清洗详细教程——pandas

    前言 在不同行业中 我们经常会遇到一个麻烦的问题 数据清洗 尤其是当我们需要处理客户编码异常数据时 这个问题变得尤为重要 想象一下 许多银行都是以客户为单位管理数据的 因此每个客户都有一个独特的编码 在处理这些数据时 我们常常会面临以下问题
  • 前端常用的CSS工具库

    1 animista 在线查看自己需要的动画效果 比较常用 直接复制代码即可 官网 Animista CSS Animations on Demand 2 Animate css是一个现成的跨浏览器动画工具库 可用于您的 Web 项目 非常
  • 攻防世界:command_execution

    首先掌握命令执行漏洞 Command Execution 的知识 命令执行漏洞即使用者可以直接在Web应用中执行系统命令 从而获取敏感信息或者拿下shell权限 其造成的原因是Web服务器对用户输入命令安全检测不足 比如没加waf 导致恶意
  • matlab 指定坐标轴,matlab设置坐标轴范围

    设置x轴和y轴为想要的显示范围 可以使用set函数 以x轴的显示范围为0到10 y轴的显示范围为90到101为例 设置x轴范围和刻度 set gca XLim 0 10 X轴的数据显示范围 set gca XTick 0 1 10 设置要显
  • Flutter键盘遮挡输入框问题

    以下代码是在网上看到的 忘记具体的出处了 请谅解 作者 Created by H on 2019 1 23 11 08 介绍 解决输入框被遮挡问题 import package flutter material dart import pa