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

Flutter声明crazy变量后TextFormField无法输入问题求助

问题原因及解决办法
  • Form的Key类型不匹配:你声明的formKey类型是GlobalKey<MyHomePageState>,但Form组件要求的关联Key类型是GlobalKey<FormState>,类型错误导致Form无法正确管理TextFormField的输入状态。
  • 变量声明位置错误:formKey和crazy都定义在build方法内部,每次组件重建(比如输入文本触发的状态更新)都会重新初始化这两个变量,直接导致TextFormField的输入状态被重置,无法持续输入内容。

修正后的代码

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: MyHomePage(),
  ));
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  // 将formKey改为成员变量,修正为Form要求的类型
  final formKey = GlobalKey<FormState>();
  // 将crazy改为成员变量,避免每次build重新初始化
  late double crazy;

  @override
  void initState() {
    super.initState();
    // 在initState中初始化需要context的变量
    crazy = MediaQuery.of(context).size.width;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 100,
      ),
      body: SingleChildScrollView(
        child: Form(
          key: formKey,
          child: TextFormField(
            decoration: const InputDecoration(
              labelText: '现在可以正常输入了',
            ),
          ),
        ),
      ),
    );
  }
}

额外说明

如果crazy需要响应屏幕尺寸变化,可以把初始化逻辑放到didChangeDependencies方法中,这样当屏幕尺寸改变时会自动重新计算:

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  crazy = MediaQuery.of(context).size.width;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:02:24