颤振错误:<异步挂起>

Posted

技术标签:

【中文标题】颤振错误:<异步挂起>【英文标题】:Error in flutter : <asynchronous suspension> 【发布时间】:2021-09-18 21:30:20 【问题描述】:

我想在产品添加成功后显示一个对话框,但是当我单击“添加到购物车”按钮时,我收到了图像中的那种错误。

这个对话框想要使用 httpException 显示,在我使用这个 httpExcetion 的 product_detailpage.dart 页面中,我使用了虚线。

这是我的 cart_api.dart 页面


import 'dart:convert';

import 'package:hospital/CartPage/Cart_Api/cart_http_exception.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;

Future add_to_cart_fn(
    String quantity, String plistId, String uid, String sid) async 
  var url = Uri.parse(
      '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCart&uid=60daaedd3b9f8751161');
  print('add_to_cart_url:' + url.toString());
  final response = await http.post(url, headers: 
    "Accept": "Application/json"
  , body: 
    "quantity": quantity,
    "plistId": plistId,
    "uid": uid,
    "sid": sid,
  );
  print("ae" + response.body);

  final convertderDatatoJson = jsonDecode(response.body);
  try 
    if (convertderDatatoJson['status'] == "true") 
      print('status' + convertderDatatoJson['status']);
      print('msg' + convertderDatatoJson['msg']);
      throw HttpException(convertderDatatoJson['msg']);
    
   catch (e) 
    throw e;
  

  return convertderDatatoJson;


这是我的 httpException.dart 页面

class HttpException implements Exception 
  final msg;

  HttpException(this.msg);

  @override
  String toString() 
    // TODO: implement toString
    return msg;
  



这是我的 product_detailPage.dart 页面,

import 'dart:convert';

import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:hospital/CartPage/Cart_Api/cart_api.dart';
import 'package:hospital/CartPage/Cart_Api/cart_http_exception.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/ProductDetailsPage/product_detailPage.dart';
import 'package:hospital/ProductDetailsPage/related_product_page.dart';
import 'package:hospital/SecondSection/Medicine/medicine_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;
import 'package:line_icons/line_icons.dart';
import 'package:provider/provider.dart';

class DetailPage extends StatefulWidget 
  final plistId;

  const DetailPage(Key key, this.plistId) : super(key: key);
  @override
  _DetailPageState createState() => _DetailPageState();


class _DetailPageState extends State<DetailPage> 
  final GlobalKey<FormState> _formKey = GlobalKey();
  int quantity = 1;
  var response;

  var detailPageApi;

  @override
  void initState() 

    super.initState();

    fetchData(widget.plistId);
  

  fetchData(var consultWithDoctor) async 
a2rTokenKey=carpet1234');

    var api = Uri.parse(
        '$ecommerceBaseUrl/productListApi.php?a2rTokenKey=$a2rTokenKey&plistId=$widget.plistId');

    response = await http.get(
      api,
    );
    print("detailPageApi " + api.toString());
    print("detailPageBody " + response.body);

    // in double quotes drink is key value of json

    detailPageApi = jsonDecode(response.body);

    print("detailPagelist " + detailPageApi.toString());
    // return doctorDetailsApi;
    setState(() );
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        backgroundColor: kGreen,
        title: Text(
          "Details",
          style: TextStyle(fontStyle: FontStyle.italic),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.shopping_cart),
            // onPressed: () => print("open cart"),
            onPressed: () 
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => Cartpage()),
              );
            ,
          ),
          DropDownMenu(),
        ],
      ),
      body: Container(
        child: response != null
            ? ListView.builder(
                // itemCount: categoryApi.length.clamp(0, 3),//THis is for showed minimun length of item listview.builder flutter
                itemCount: detailPageApi.length.clamp(0, 1),
                scrollDirection: Axis.vertical,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) 
                  var details = detailPageApi[index];
                  if (details['num'] == 0) 
                    return Center(
                      child: CircularProgressIndicator(
                        backgroundColor: Colors.white,
                      ),
                    );
                  
                  return Column(
                    children: <Widget>[
                      Hero(

                        tag: "1",
                        child: SizedBox(
                          height: 300.0,
                          width: 300.0,
                          child: Carousel(
                            boxFit: BoxFit.cover,
                            autoplay: false,
                            animationCurve: Curves.fastOutSlowIn,
                            animationDuration: Duration(milliseconds: 800),
                            dotSize: 6.0,
                            dotIncreasedColor: Colors.black,
                            dotBgColor: Colors.transparent,
                            // dotPosition: DotPosition.topRight,
                            dotVerticalPadding: 10.0,
                            showIndicator: true,
                            indicatorBgPadding: 7.0,
                            images: [
                              NetworkImage(details['pImgImg']),
                              
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 50,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Name :",
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 1.5,
                                  fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Flexible(
                              child: Text(
                                // widget.details,
                                details['productName'],
                                style: TextStyle(
                                    fontSize: 17,
                                    height: 1.5,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Details :",
                              style: TextStyle(
                                  fontSize: 18,
                                  height: 1.5,
                                  fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Flexible(
                              child: Text(
                                // widget.details,
                                details['productDescription'],
                                style: TextStyle(
                                    fontSize: 17,
                                    height: 1.5,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 20, right: 20),
                        child: Row(
                          children: <Widget>[
                            Text(
                              "Price :",
                              style: TextStyle(
                                  fontSize: 18, fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  // "Rs " + widget.pPromotionPrice,
                                  "Rs 55.0",
                                  style: TextStyle(
                                      fontSize: 17,
                                      fontWeight: FontWeight.w500),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Text(
                                  // "Rs " + widget.pPrice,
                                  "Rs 100",
                                  style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w500,
                                      // color: warning,
                                      decoration: TextDecoration.lineThrough),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      
                      Padding(
                        padding: const EdgeInsets.only(right: 20, left: 20),
                        child: Row(
                          children: <Widget>[
                            Text(
                              "Qty :",
                              style: TextStyle(
                                  fontSize: 17, fontWeight: FontWeight.w500),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Row(
                              children: <Widget>[
                                InkWell(
                                  onTap: () 
                                    if (quantity > 1) 
                                      setState(() 
                                        quantity = --quantity;
                                      );
                                    

                                    // minus here
                                  ,
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      LineIcons.minus,
                                      size: 15,
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                Text(
                                  quantity.toString(),
                                  style: TextStyle(fontSize: 16),
                                ),
                                SizedBox(
                                  width: 15,
                                ),
                                InkWell(
                                  onTap: () 
                                    setState(() 
                                      quantity = ++quantity;
                                    );
                                    // minus here
                                  ,
                                  child: Container(
                                    width: 25,
                                    height: 25,
                                    decoration: BoxDecoration(
                                        // border: Border.all(color: primary),
                                        shape: BoxShape.circle),
                                    child: Icon(
                                      LineIcons.plus,
                                      size: 15,
                                    ),
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 50,
                      ),
                      InkWell(
                        onTap: () async 
                   ---------------------------------------------
                     //here show my msg using dialog box
                          try  on HttpException catch (e) 
                            print('hiii');
                           
                            var errorMessage = 'Authentication Failed';
                            if (e.toString().contains(
                                'Product Succesfully Added to Cart')) 
                              errorMessage =
                                  'Product Succesfully Added to Cart';
                              print(errorMessage);
                              _showerrorDialog(errorMessage);
                            
                           catch (error) 
                            var errorMessage = 'Please try again later';
                            _showerrorDialog(errorMessage);
                          
                         ------------------------------------------------
                          var qty = quantity.toString();
                          var plistId = widget.plistId;
                          print('pplistid' + plistId);

                          var uid = var_uid.toString();
                          var sid = var_sid.toString();
                          print('uuid' + uid);
                          print('ssid' + sid);

                          var response =
                              await add_to_cart_fn(qty, plistId, uid, sid);

                          print("rsp: " + response['status']);
                        ,
                        // ,
                        child: Padding(
                          padding: EdgeInsets.only(left: 20, right: 20),
                          child: Container(
                            height: 45,
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: kGreen,
                                borderRadius: BorderRadius.circular(30)),
                            child: Center(
                              child: Text(
                                "ADD TO CART",
                                style: TextStyle(
                                  color: kWhite,
                                  fontSize: 20,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: 20.0),
                      // SomeMedicinePage(),
                      RelatedProductPage(plistId: widget.plistId)
                    ],
                  );
                )
            : Center(
                child: CircularProgressIndicator(
                  backgroundColor: Colors.white,
                ),
              ),
      ),
    );
  

  void _showerrorDialog(String message) 
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(
          'An Error Occurs',
          style: TextStyle(color: Colors.blue),
        ),
        content: Text(message),
        actions: <Widget>[
          FlatButton(
              child: Text('Okay'),
              onPressed: () => Navigator.of(context, rootNavigator: true).pop())
        ],
      ),
    );
  


【问题讨论】:

【参考方案1】:

找到这个答案(不是我的):

不是问题的指示,它只是表明代码执行不是逐行执行的同步代码,而是从调用堆栈中的某个位置开始的已完成 Future 的回调

来源: https://***.com/questions/60658945/asynchronous-suspension-in-stacktrace-output-in-flutter#:~:text=is%20not%20an,some%20position%20in%20the%20callstack.

【讨论】:

【参考方案2】:

将该 api 或平台特定代码包装在 catch (e) 上的 try 和 catch 块中 do your stuff here error handling

【讨论】:

以上是关于颤振错误:<异步挂起>的主要内容,如果未能解决你的问题,请参考以下文章

<异步挂起>flutter 医生时的注释 --android-licenses -v

颤振异步调用不会在 initState() 中异步运行

Web Api + HttpClient:异步模块或处理程序已完成,而异步操作仍处于挂起状态

每当使用异步时,ASP.Net MVC 4 控制器就会挂起

在 Node.js 承诺的环境中监控挂起的异步操作

颤振和块异步产量