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

Flutter中TextField转数字求和遇FormatException错误求助

问题分析与解决方案

核心问题

  1. FormatException 错误:你把inputToData、inputToData2、addition定义在State类外部,初始化时input1.text和input2.text可能为空(即便设置初始值'0',类外初始化时机早于控制器绑定,依然可能读取空值),直接用int.parse会抛出无效数字异常。
  2. 实时更新失效:未监听TextField的实时输入变化,onSubmitted仅在用户提交输入(比如按回车)时触发,无法实现实时更新;且求和逻辑未在setState内执行,状态变化不会触发UI重建。

修正步骤

  • 将控制器、计算变量移至State类内部,纳入状态管理。
  • 初始化控制器时设置初始文本'0',确保初始值有效。
  • 使用onChanged监听输入变化,每次输入修改时调用setState重新计算求和结果。
  • 用int.tryParse替代int.parse,处理可能的无效输入(比如空值、非数字),避免异常。

完整修正代码

class _HomePageState extends State<HomePage> {
  // 将控制器移至State内部,并设置初始值
  final TextEditingController input1 = TextEditingController(text: '0');
  final TextEditingController input2 = TextEditingController(text: '0');
  late int addition;

  @override
  void initState() {
    super.initState();
    // 初始化求和结果
    _calculateSum();
    // 可选:监听控制器文本变化(替代onChanged)
    // input1.addListener(() => _calculateSum());
    // input2.addListener(() => _calculateSum());
  }

  @override
  void dispose() {
    // 释放控制器资源
    input1.dispose();
    input2.dispose();
    super.dispose();
  }

  // 封装求和逻辑
  void _calculateSum() {
    setState(() {
      // 使用tryParse处理无效输入,转换失败时默认0
      int num1 = int.tryParse(input1.text) ?? 0;
      int num2 = int.tryParse(input2.text) ?? 0;
      addition = num1 + num2;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const AppBar(title: Text("deneme")),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(
          children: [
            Container(
              height: 50,
              width: 280,
              color: Colors.blue,
              child: SizedBox(
                height: 40,
                width: 100,
                child: TextField(
                  keyboardType: TextInputType.number,
                  controller: input1,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 30,
                  ),
                  // 输入变化时触发求和
                  onChanged: (_) => _calculateSum(),
                ),
              ),
            ),
            const Divider(thickness: 1),
            Container(
              height: 50,
              width: 280,
              color: Colors.orange,
              child: TextField(
                keyboardType: TextInputType.number,
                controller: input2,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                ),
                onChanged: (_) => _calculateSum(),
              ),
            ),
            const Divider(thickness: 1),
            Container(
              height: 50,
              width: 280,
              color: Colors.orange,
              child: Text(
                addition.toString(),
                style: const TextStyle(fontSize: 30, color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

额外说明

  • 代码中提供了两种监听输入变化的方式:onChanged直接绑定到TextField,或者通过控制器的addListener方法,二者选其一即可。
  • int.tryParse在输入无效时返回null,配合?? 0可以将无效输入默认转为0,避免崩溃。
  • 记得在dispose方法中释放控制器资源,防止内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:06:40