首页 > 解决方案 > 为什么当我的 TextFormField 获得焦点时我的页面会重新加载?

问题描述

当我触摸 TextField 时,它会自动重新加载我的页面,我不能放一个字母

我尝试了很多方法,例如删除 setState 并且它可以工作,但我需要它才能将我的值保存在数据中,我发现该方法可以将我的未来置于 initstate 中,但我不知道该怎么做,我不是确定这是解决方案。我在 StateFulWidget 我也使用 globalKey 但它在构建方法之外。

这是我的代码:

class _UpdateProfileState extends State<UpdateProfile> {

 final GlobalKey<FormState> _formKey  = GlobalKey<FormState>();

...
//My future
 body: Form(
        key: _formKey,
       child: Column(
          children: <Widget>[
            FutureBuilder<DocumentSnapshot>(
              future: Users
                  .doc(uid)
                  .get(),
              builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                if (snapshot.hasError) {
                  return Text("Something went wrong");
                }
                if (snapshot.hasData && !snapshot.data!.exists) {
                  return Text("Document does not exist");
                }
                if (snapshot.connectionState == ConnectionState.done) {
                  return displayUserInformation(context, snapshot);
                } else {
                  return SizedBox(height: 400,
                      child: Center(child: CircularProgressIndicator()));
                }
              },
            ),
          ],
        ),
     ),
    );
  }

...
 //And this is My textFormField
 Padding(
           padding: const EdgeInsets.all(16.0),
           child: TextFormField(
             onChanged: (value) =>
                 setState(() => _name = value.trim()),
             initialValue: "${data['displayName'].toString()}",
               cursorColor: DarkTurquoise,
             decoration: InputDecoration(
               labelText: 'Name',
               labelStyle: TextStyle(
                 color: SeaTurquoise
               ),
               focusedBorder: UnderlineInputBorder(
                 borderSide:  BorderSide(color: SeaTurquoise, width: 2.0),),
               enabledBorder: UnderlineInputBorder(
                 borderSide: BorderSide(color: DarkGrey),
               ),
             ),
           ),
         ),

谢谢您的回答

标签: firebaseflutterdartfuturetextformfield

解决方案


将下面的代码放在您用于提交表单的按钮上,它将从您的文本字段中获取焦点并将其提供给您可以使用的按钮,您也可以使用焦点节点转到此链接以了解更多信息

       FocusScope.of(context).unfocus();
       FocusScope.of(context).requestFocus(new FocusNode());

推荐阅读