Flutter 上无法输入 TextFormField

问题描述 投票:0回答:1

我尝试使用 Flutter 创建表单。然而,在我声明了一个疯狂的变量后,我无法输入到 TextFormField 中。我在React中也有过类似的经历,但我不知道最好的解决方案。我需要疯狂和 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> {
  @override
  Widget build(BuildContext context) {
    final formKey = GlobalKey<MyHomePageState>();
    var crazy = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 100,
      ),
      body: SingleChildScrollView(
        child: Form(
          key: formKey,
          child: TextFormField(
            decoration: const InputDecoration(
              labelText: 'Why I can not input?',
            ),
          ),
        ),
      ),
    );
  }
}

flutter
1个回答
0
投票

那是因为您在

formKey
方法中定义了
build
。因此,当键盘开始打开时,
build
方法会再次执行,再次重新创建新的
formKey
并将整个
Form
状态重置为初始状态。解决方案是在状态类中初始化
formKey
,而不是在
build
方法中。

class MyHomePageState extends State<MyHomePage> {
  // initialize here, not in the build method
  final formKey = GlobalKey<MyHomePageState>();
  
  @override
  Widget build(BuildContext context) {
    var crazy = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 100,
      ),
      body: SingleChildScrollView(
        child: Form(
          key: formKey,
          child: TextFormField(
            decoration: const InputDecoration(
              labelText: 'Why I can not input?',
            ),
          ),
        ),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.