簡體   English   中英

具有默認文本的TextFormField

[英]TextFormField with default text

我想擁有一些FormTextFields,其中包含一些用戶可以更改的默認文本。 我的問題是,修改了字段后,如果按一下另一個字段或按鈕,一切都很好,但是,如果按鍵盤上的“完成”按鈕,則會返回默認文本,刪除用戶插入的新內容。 到目前為止,這是我所做的:

class _LoginSettingsViewState extends State<LoginSettingsView> {

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

  var _userTextController = new TextEditingController();

@override
  Widget build(BuildContext context) {

    _userTextController.text = "test";

 return Scaffold(

      appBar: AppBar(
        title: Text("Settings"),
      ),

      body: ListView(
        children: <Widget>[
          new Container(
            margin: EdgeInsets.only(
              left: 10.0,
              right: 10.0,
              top: MediaQuery.of(context).size.height / 10
            ),
            child: Form(
                key: _formKey,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      decoration: _fieldDecoration("user", null),
                      controller: _userTextController,
                      validator: (val) => val.isEmpty ? "Insert user" : null,
                      onSaved: (val){
                        print(val);
                      },
                    ),

您是在build方法中設置默認文本,每次重新構建UI時,都會調用build方法,因此您可以放回默認文本。

將您的初始化initState方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}

也不要忘記布置控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}

暫無
暫無

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

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