如何在Flutter中删除警报对话框

时间:2020-01-19 03:05:48

标签: flutter

我在验证OTP后创建了一个用于OTP验证的警报对话框,我将其关闭,然后又创建了另一个对话框以进行数据处理...然后关闭它。

结果:- 通过调用Navigator.of(context).pop();进行OTP验证后,第一个OTP对话框关闭,然后弹出第二个对话框,但在调用Navigator.of(context).pop();后没有关闭

我想做什么:

  1. 验证OTP(Works)后,关闭OTP对话框
  2. 打开进度对话框(Works)
  3. 在Firebase存储中上传配置文件后将其关闭(无效)

请帮助我解决此问题。

预先感谢!

1 个答案:

答案 0 :(得分:2)

您可能忘记了代码中的await

尝试一下,

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _otpCtrl = TextEditingController();

  void dispose() {
    _otpCtrl.dispose();
    super.dispose();
  }

  Future<void> _verifyOTP() async {
    final String otp = await _inputOtp();
    String otpValidationError;
    if (otp != null) otpValidationError = await _sendOtpVerifyRequest();
    print(otpValidationError);
  }

  Future<String> _sendOtpVerifyRequest() async {
    showDialog(
      context: context,
      builder: (context) {
        return Center(child: CircularProgressIndicator());
      },
    );
    await Future.delayed(Duration(seconds: 2)); //TODO: Do post request here
    Navigator.pop(context);
    return null;
  }

  Future<String> _inputOtp() async {
    final flag = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("Enter OTP"),
          content: TextField(
            controller: _otpCtrl,
            decoration: InputDecoration(
              hintText: "x x x x x x",
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text("Cancel"),
              onPressed: () {
                Navigator.pop(context, false);
              },
            ),
            FlatButton(
              child: Text("Confirm"),
              onPressed: () {
                Navigator.pop(context, true);
              },
            ),
          ],
        );
      },
    );
    if (flag == true)
      return _otpCtrl.text;
    else
      return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: _verifyOTP,
          child: Text("Click Here"),
        ),
      ),
    );
  }
}