Flutter textFiled 输入始终将更改保存在 AlertDialog 小部件中

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

我在文本字段中创建取消按钮时遇到问题。

但总是保存更改取消按钮和提交按钮

如果我删除取消按钮代码,当点击背景弹出警报对话框时,它也会保存文本字段的更改

我找到了一些视频和文档,但代码没有什么不同

https://www.youtube.com/watch?v=TpW7nLL57uQ

下面:我的AlertDialog代码

Future<void> editField(String field) async {
    String newValue = '';
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[100],
        title: Text(
          "Edit $field",
          style: const TextStyle(color: Colors.black),
        ),
        content: TextField(
          autofocus: true,
          style: const TextStyle(color: Colors.black),
          decoration: InputDecoration(
            hintText: "Enter new $field",
            hintStyle: const TextStyle(color: Colors.grey),
          ),
          onChanged: (value) {
            newValue = value;
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(newValue),
            child: const Text('Submit'),
          ),
        ],
      ),
    );
    if (newValue.trim().isNotEmpty) {
      await userCollection.doc(currentUser.email).update({field: newValue});
    }
  }
flutter firebase textfield flutter-alertdialog
2个回答
0
投票

试试这个代码:

  Future<void> editField(String field) async {
    String newValue = '';
    
    await showDialog(
      context: context,
      builder: (context) {
        String dialogValue = '';
        return AlertDialog(
          backgroundColor: Colors.grey[100],
          title: Text(
            "Edit $field",
            style: const TextStyle(color: Colors.black),
          ),
          content: TextField(
            autofocus: true,
            style: const TextStyle(color: Colors.black),
            decoration: InputDecoration(
              hintText: "Enter new $field",
              hintStyle: const TextStyle(color: Colors.grey),
            ),
            onChanged: (value) {
              dialogValue = value;
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(dialogValue),
              child: const Text('Submit'),
            ),
          ],
        );
      },
    ).then((value) {
      newValue = value;
    });
    
    if (newValue.trim().isNotEmpty) {
      await userCollection.doc(currentUser.email).update({field: newValue});
    }
  }

0
投票

将此代码放入提交时,因为这在任一条件下都会执行。

  if (newValue.trim().isNotEmpty) {
     await userCollection.doc(currentUser.email).update({field: newValue});
  }
© www.soinside.com 2019 - 2024. All rights reserved.