【问题标题】:Textfield returning null; bypassing await文本字段返回 null;绕过等待
【发布时间】:2020-07-09 10:35:04
【问题描述】:

我正在制作一个计数器应用程序,并希望能够通过使用弹出输入框从用户那里获取输入来更改应用程序栏的标题。

我试图让用户在 AlertDialog 中输入一个名称(字符串),其中包含 textfield,并尝试通过 在主页中接收字符串>为按下确认按钮时返回输入字符串的弹出窗口定义一个函数。我在主页的 onPressed() 中使用 await 为这个函数分配一个变量,然后在 snackbar 中显示字符串变量的变化。但是,当我点击文本字段时,小吃栏就会出现,甚至没有提交或点击确认按钮。看起来等待不起作用,或者由于某种原因,Alertdialog 的父函数在我点击文本字段后立即返回 null。

import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(


     home: CounterApp(),
    ));

class CounterApp extends StatefulWidget {

  @override
  _CounterAppState createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {


  int num = 0;
  String name = 'MyCounter-1';



 Future<String> changeName() async {

    final _controller = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15)
          ),
          title: Text('Change counter name'),
          content: TextField(
            controller: _controller,
            onSubmitted: (str) {
              //Navigator.of(context).pop(str);
            },
          ),
          actions: <Widget>[
            FlatButton(
              onPressed: () {
                Navigator.of(context).pop(_controller.text.toString());
              },
              child: Text(
                'Confirm',
                style: TextStyle(
                  fontSize: 18.0,
                ),
              ),
            ),
            FlatButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(
                'Cancel',
                style: TextStyle(
                  fontSize: 18.0,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  void snackBar(BuildContext context, String string) {
    final snackbar = SnackBar(content: Text('Counter renamed to $string'),);
    Scaffold.of(context).showSnackBar(snackbar);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(name),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            onPressed: () {
              setState(() {
                num = 0;
              });
            },
            icon: Icon(
              Icons.refresh,
              size: 35.0,
            ),
          ),
          Builder(
            builder: (context) => IconButton(
              onPressed: () async {
                setState(() async {
                  name = await changeName();
                  snackBar(context, name);
                });
              },
              icon: Icon(
                Icons.edit,
                size: 35.0,
              ),
            ),
          ),
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            flex: 2,
            child: Container(
              child: Center(child: Text(
                '$num',
                style: TextStyle(
                  fontSize: 75,
                ),
              )),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
            child: RaisedButton(
              onPressed: () {
                setState(() {
                  num += 1;
                });
              },

              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.0)
              ),
              color: Colors.blue,
              child: Text(
                '+',
                style: TextStyle(
                  fontSize: 100.0,
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
            child: RaisedButton(
              onPressed: () {
                setState(() {
                  num -= 1;
                });
              },
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0)
              ),
              color: Colors.grey,
              child: Text(
                '-',
                style: TextStyle(
                  fontSize: 100.0,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

只要我点击编辑按钮,就会发生这种情况: Image of problem

【问题讨论】:

    标签: flutter asynchronous async-await android-alertdialog future


    【解决方案1】:

    只需在showDialog()前添加await关键字,最后添加return语句,如下代码所示。

    Future<String> changeName() async {
        final _controller = TextEditingController();
    
        await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              shape:
                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
              title: Text('Change counter name'),
              content: TextField(
                controller: _controller,
                onSubmitted: (str) {
                  //Navigator.of(context).pop(str);
                },
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(_controller.text.toString());
                  },
                  child: Text(
                    'Confirm',
                    style: TextStyle(
                      fontSize: 18.0,
                    ),
                  ),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(
                    'Cancel',
                    style: TextStyle(
                      fontSize: 18.0,
                    ),
                  ),
                ),
              ],
            );
          },
        );
    
        return _controller.text;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      • 2011-10-22
      • 2015-04-22
      • 2014-10-06
      • 2013-07-04
      • 2020-04-01
      • 2012-05-07
      相关资源
      最近更新 更多