You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter TextField实现iOS端显示最后输入字符的密码隐藏效果

实现iOS端密码输入框最后字符短暂显示的效果

默认情况下,Flutter的TextFormField在iOS和Android上的密码隐藏行为存在差异:Android会短暂显示最后输入的字符,而iOS则直接隐藏所有输入。要让iOS端实现和Android一致的效果,你可以通过自定义输入控制逻辑来实现。

具体实现思路

通过TextEditingController监听文本变化,维护一个状态变量控制密码是否隐藏,当有新字符输入时,短暂显示最后一个字符,延迟一段时间后再切换回完全隐藏状态,同时注意清理定时器避免内存泄漏。

示例代码

import 'dart:async';
import 'package:flutter/material.dart';

class PasswordInputField extends StatefulWidget {
  final ValueChanged<String>? onPasswordChanged;
  final String? hintText;

  const PasswordInputField({
    Key? key,
    this.onPasswordChanged,
    this.hintText,
  }) : super(key: key);

  @override
  State<PasswordInputField> createState() => _PasswordInputFieldState();
}

class _PasswordInputFieldState extends State<PasswordInputField> {
  final TextEditingController _controller = TextEditingController();
  bool _isObscure = true;
  Timer? _hideTimer;

  @override
  void initState() {
    super.initState();
    _controller.addListener(_handleTextChange);
  }

  void _handleTextChange() {
    final currentText = _controller.text;
    if (currentText.isNotEmpty) {
      // 显示最后输入的字符
      setState(() => _isObscure = false);
      // 清除之前的定时器,避免重复触发
      _hideTimer?.cancel();
      // 1秒后恢复隐藏状态
      _hideTimer = Timer(const Duration(seconds: 1), () {
        if (mounted) setState(() => _isObscure = true);
      });
    }
    widget.onPasswordChanged?.call(currentText);
  }

  @override
  void dispose() {
    _controller.dispose();
    _hideTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: _controller,
      obscureText: _isObscure,
      enableSuggestions: false,
      autocorrect: false,
      decoration: InputDecoration(
        hintText: widget.hintText ?? '请输入密码',
      ),
      onChanged: (text) {
        // 处理清空输入的情况
        if (text.isEmpty) setState(() => _isObscure = true);
        widget.onPasswordChanged?.call(text);
      },
    );
  }
}

使用方式

直接在页面中引入这个自定义组件即可:

PasswordInputField(
  hintText: '请输入登录密码',
  onPasswordChanged: (password) {
    // 这里处理密码输入后的逻辑
  },
)

这个方案通过状态切换和定时器延迟,模拟了Android端的密码显示逻辑,同时兼容iOS和Android平台。

内容的提问来源于stack exchange,提问作者Apri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:07:39