flutter - flutter 错误 : <asynchronous suspension>

标签 flutter dart flutter-layout flutter-dependencies flutter-test

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

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

enter image description here 这是我的 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())
        ],
      ),
    );
  }
}

最佳答案

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

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

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

关于flutter - flutter 错误 : <asynchronous suspension>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68301218/

相关文章:

flutter - 根据最小尺寸包裹小部件,然后拉伸(stretch)它们以填充可用宽度

file - Flutter - 保存文件

dart - 异步调用值首次为NULL,从而在构建MainPage时导致断言错误(窗口小部件脏)

listview - 如何在AnimatedBuilder中制作ListView?

flutter - 在 Flutter 中显示用户友好的错误页面而不是异常

Flutter 加载图片资源太慢

flutter - 通过 android 和 ios 中的几个按钮在社交媒体上分享链接

android - 数据消息与通知消息,(可折叠和不可折叠混淆)

Flutter:调试小部件重建的正确方法

flutter - 如何在GridView中增加卡片大小