Флаттер: будущее не вернется после закрытия диалогового окна - PullRequest
0 голосов
/ 30 января 2020

Я создал метод http во флаттере, как показано ниже:

  Future<void> addProduct(Product product) {
    const url = 'https://flutter-shop-3de16.firebaseio.com/products';
    return http
        .post(
      url,
      body: json.encode({
        'title': product.title,
        'description': product.description,
        'imageUrl': product.imageUrl,
        'price': product.price,
        'isFavorite': product.isFavorite,
      }),
    )
        .then((response) {
      ...
      notifyListeners();
    }).catchError((error) {
      print(error);
      throw error;
    });
  }

Я знаю, что мой url неверен, потому что я хочу получить ошибку.

В .catchError я выдаю ошибку, а на главной странице провайдера я использовал addProduct, например:

      Provider.of<Products>(context, listen: false)
          .addProduct(_editedProduct)
          .catchError((error) {
        return showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Text('An error occurred!'),
            content: Text('Something went wrong.'),
            actions: <Widget>[
              FlatButton(
                child: Text('Okay'),
                onPressed: () {
                  Navigator.of(ctx).pop();
                },
              )
            ],
          ),
        );
      }).then((_) {
        print('after catch accoured');
        setState(() {
          _isLoading = false;
        });
        Navigator.of(context).pop();
      });
    }
  }

I catchError Я получил ошибку, и я показываю диалоговое окно с предупреждением . После нажатия на кнопку Okay я хочу выполнить then блок, поэтому я вернул showDialog, потому что он возвращает будущее.

Но я не знаю, почему

.then((_) {
            print('after catch accoured');
            setState(() {
              _isLoading = false;
            });
            Navigator.of(context).pop();
          });
        }

Нет запустить после закрытия диалогового окна с предупреждением?

Ответы [ 2 ]

0 голосов
/ 08 мая 2020

Ниже код должен решить вашу проблему. Перемещение оператора затем после диалога заставит его работать снова.

    Provider.of<Products>(context, listen: false)
        .addProduct(_editedProduct)
        .catchError((error) {
      return showDialog(
        context: context,
        builder: (ctx) =>
            AlertDialog(
              title: Text('An error occurred!'),
              content: Text('Something went wrong.'),
              actions: <Widget>[
                FlatButton(
                  child: Text('Okay'),
                  onPressed: () {
                    Navigator.of(ctx).pop();
                  },
                )
              ],
            ),
      ).then((_) {
        print('after catch accoured');
        setState(() {
          isLoading = false;
        });
        Navigator.of(context).pop();
      });;
    });
0 голосов
/ 30 января 2020

Блок then будет работать после основного будущего; он не будет работать после catchError. Если вы хотите запустить фрагмент кода после catchError, используйте блок whenComplete.

  Provider.of<Products>(context, listen: false)
          .addProduct(_editedProduct)
          .catchError((error) {
        return showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Text('An error occurred!'),
            content: Text('Something went wrong.'),
            actions: <Widget>[
              FlatButton(
                child: Text('Okay'),
                onPressed: () {
                  Navigator.of(ctx).pop();
                },
              )
            ],
          ),
        );
      }).whenComplete(() { // This will run after execution
        print('after catch accoured');
        setState(() {
          _isLoading = false;
        });
        Navigator.of(context).pop();
      });
    }
  }
...