簡體   English   中英

Flutter 關閉鍵盤時清除 TextFormFields

[英]Flutter TextFormFields clear when dismissing keyboard

幾乎就是我在標題中描述的內容。 當應用程序啟動時,我有一堆從 Firebase 填充的 TextFormFields。

用戶應該能夠更新這些,完成后,單擊提交按鈕更新數據庫。 數據庫代碼一切正常,但是存在一些錯誤,其工作方式如下:

TextFormField1:   "New Text Entered"
TextFormField2:   "Some more text"
TextFormField3:   "Another update here"

現在我們到了需要關閉鍵盤的地步,這樣我們才能看到下面的提交按鈕。 一旦你點擊向下的小箭頭關閉鍵盤,上面的所有更改都會恢復到原來的 state。

有人見過這個嗎?

我在運行時在這些字段中預填充數據,您可以編輯和更新文本,一切正常……除非您最小化鍵盤。

請告訴我 Flutter 並沒有做一些根本上愚蠢的事情,比如每次你要求鍵盤輸入 go 時從頭開始重新加載下面的小部件......感覺有點像。

是的。 它一直發生在我身上。 這是因為當底部插圖(由於鍵盤)發生變化時屏幕會重建。

  1. TextFormField(s)包含在Form中並為其提供全局鍵。
  2. 使用局部變量來存儲 TextFormField 的值。 在 onChanged 方法中更新它。 全部完成!

為方便起見,我將附上代碼。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LoginScreen(),
    );
  }
}

// Login Screen
class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
  static GlobalKey<FormState> _loginScreenFormKey = GlobalKey<FormState>();
}

class _LoginScreenState extends State<LoginScreen> {
  String username;
  String password;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Form(
          key: LoginScreen._loginScreenFormKey,
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  hintText: 'Enter username',
                ),
                onChanged: (value) {
                  setState(() {
                    username = value;
                  });
                },
              ),
              TextFormField(
                decoration: InputDecoration(
                  hintText: 'Enter username',
                ),
                onChanged: (value) {
                  setState(() {
                    password = value;
                  });
                },
                obscureText: true,
              ),
              RaisedButton(
                onPressed: () {
                  LoginScreen._loginScreenFormKey.currentState.save();
                },
                child: Text('submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

這是我的解決方案:將 TextEditingController 變量從“build”方法內部移動到“build”方法外部。 參考圖片解決方案

The class that includes those TextFormFields should extends State of StatefulWidget, the local state will be cleared if the dismiss of keyboard causes those fields re-render, hence you need StatefulWidget to save the local state so that it won't be re-rendered

將 StatelessWidget 轉換為 StatefulWidget。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM