【问题标题】:My catch error in flutter is not working as I want it to. I want to display error message when the error appears but it is not showing up我在颤动中的捕获错误没有按我想要的那样工作。我想在出现错误但未显示时显示错误消息
【发布时间】:2022-01-15 11:56:14
【问题描述】:

我在 addproduct 对象中添加了 catch 错误,并将它添加到我的屏幕中,以便我可以看到错误消息。所以我故意犯了一个错误,在解析时从我的firebase服务器中删除'.json',因此它没有保存并给出错误enter image description here 这是错误:

但不知何故,错误消息并未在应用程序上向用户显示。

产品代码(添加产品对象):

class Products with ChangeNotifier {
  List<Product> _items = [
    Product(
      id: 'p1',
      title: 'Red Shirt',
      description: 'A red shirt - it is pretty red!',
      price: 29.99,
      imageUrl:
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
    ),
    Product(
      id: 'p2',
      title: 'Trousers',
      description: 'A nice pair of trousers.',
      price: 59.99,
      imageUrl:
          'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
    ),
    Product(
      id: 'p3',
      title: 'Yellow Scarf',
      description: 'Warm and cozy - exactly what you need for the winter.',
      price: 19.99,
      imageUrl:
          'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg',
    ),
    Product(
      id: 'p4',
      title: 'A Pan',
      description: 'Prepare any meal you want.',
      price: 49.99,
      imageUrl:
          'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-Pan.jpg',
    ),
  ];

  

  List<Product> get items {
    
    return [..._items];
  }

  

  
  Product findById(String id) {
    return _items.firstWhere((element) => element.id == id);
  }

  Future<void> addProduct(Product product) {
    var url = Uri.parse(
        'Server link without .json');
    
   return http
        .post(
      url,
      body: json.encode({
        'title': product.title,
        'description': product.description,
        'imageUrl': product.imageUrl,
        'price': product.price,
        'Favorite': product.isFavourite
      }),
    )
        .then((response) {
     
      print(jsonDecode(response.body));
      final newProduct = Product(
          description: product.description,
          id: jsonDecode(response.body)['name'],
          imageUrl: product.imageUrl,
          price: product.price,
          title: product.title);
      _items.add(newProduct);
     
      notifyListeners();
    }).catchError((error) {
      
      print(error);
      throw error;
    }); 
  }

  void updateProduct(String id, Product newProduct) {
    final prodIndex = _items.indexWhere((prod) => prod.id == id);
    if (prodIndex >= 0) {
      _items[prodIndex] =
          newProduct; 
      notifyListeners();
    } else {
      print('...');
    }
  }

 

编辑产品屏保对象代码:

void _saveForm() {
    final isValid =
        _form.currentState!.validate(); 
    if (!isValid) {
      return;
    }
    _form.currentState!.save(); 
    setState(() {
      _isLoading = true;
    });
    if (_editedProduct.id != '') {
      Provider.of<Products>(context, listen: false)
          .updateProduct(_editedProduct.id, _editedProduct);
      setState(() {
        _isLoading = false;
      });
      Navigator.of(context).pop();
    } else {
      Provider.of<Products>(context, listen: false)
          .addProduct(_editedProduct)
          .catchError((error) {
       
        return showDialog(
            context: context,
            builder: (ctx) => AlertDialog(
                  title: Text('An error Occured'),
                  content: Text('Something went wrong'),
                  actions: [
                    ElevatedButton(
                        onPressed: () {
                          Navigator.of(ctx).pop();
                        },
                        child: Text('Okay'))
                  ],
                ));
      }).then((_) {
        setState(() {
          _isLoading = false;
        });
        
        Navigator.of(context).pop();
      });
    } 

    
  }

提前致谢!!!

【问题讨论】:

    标签: firebase flutter flutter-layout flutter-dependencies flutter-web


    【解决方案1】:

    我认为如果你不返回 showDialog 问题就会解决

    .catchError((error) {
       
        showDialog(
            context: context,
            builder: (ctx) => AlertDialog(
                  title: Text('An error Occured'),
                  content: Text('Something went wrong'),
                  actions: [
                    ElevatedButton(
                        onPressed: () {
                          Navigator.of(ctx).pop();
                        },
                        child: Text('Okay'))
                  ],
                ));
      })
    

    【讨论】:

    • 您好,感谢您的帮助。警报对话框仍未出现,只是 Navigator.of(context).pop 已停止工作。
    • 试试这个。使函数异步并将等待放在 showDialog 后面
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多