TextField(在flutter中)被先前填充的值填充(无意)

fd3cxomn  于 2022-12-27  发布在  Flutter
关注(0)|答案(1)|浏览(124)

main.dart文件中单击floatingActionButton时,我将调用一个对话框小部件。
main.dart

late ShoppingListDialog dialog;

@override
void initState() {
  dialog = ShoppingListDialog();
  super.initState();
}
floatingActionButton: FloatingActionButton(
  child: Icon(
    Icons.add,
  ),
  backgroundColor: Colors.pink,
  onPressed: () {
    showDialog(
      context: context,
      builder: (BuildContext context) => dialog.buildDialog(
          context, ShoppingList(id: 0, name: '', priority: 0), true),
    );
  },
),

购物清单对话框. dart

class ShoppingListDialog {
  final txtName = TextEditingController();
  final txtPriority = TextEditingController();

  Widget buildDialog(BuildContext context, ShoppingList list, bool isNew) {
    DbHelper helper = DbHelper();
    if (!isNew) {
      txtName.text = list.name;
      txtPriority.text = list.priority.toString();
    }

    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
      title: Text((isNew) ? 'New shopping list' : 'Edit shopping list'),
      content: SingleChildScrollView(
        child: Column(
          children: [
            TextField(
                controller: txtName,
                onTap: () {},
                decoration: InputDecoration(hintText: 'Shopping List Name')),
            TextField(
              controller: txtPriority,
              keyboardType: TextInputType.number,
              decoration:
                  InputDecoration(hintText: 'Shopping List Priority (1-3)'),
            ),
            TextButton(
              child: Text('Save Shopping List'),
              onPressed: () {
                list.name = txtName.text;
                list.priority = int.parse(txtPriority.text);
                helper.insertList(list);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

第一次TextField是空的(显示提示文本),但第二次以后,它被最后使用的值填充,而我希望它们是空的,就像下面的图像,当我第二次点击floatingActionButton添加东西时,它被填充"fruits"(我以前使用的值)。

TextField应该从空开始,但它被以前使用的值填充。

2uluyalo

2uluyalo1#

下面是适合您的基本解决方案

TextButton(
  child: Text('Save Shopping List'),
  onPressed: () {
    list.name = txtName.text;
    list.priority = int.parse(txtPriority.text);
    // Clear TE Controller
    txtName.clear();
    txtPriority.clear();
    // Insert 
    helper.insertList(list);

    Navigator.pop(context);
  },
),

相关问题