Flutter问题:如何更新购物车中的商品数量?

vi4fp9gy  于 2022-12-27  发布在  Flutter
关注(0)|答案(3)|浏览(180)

我实现了添加到购物车功能,成功地将商品添加到购物车中,但当我重新加载dart页面时,购物车徽章中的计数数量没有更新,而计数数量没有更新。有人能帮助我吗?

我实现了添加到购物车功能,成功地将商品添加到购物车中,但当我重新加载dart页面时,购物车徽章中的计数数量没有更新,而计数数量没有更新。有人能帮助我吗?这是我的主页。dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:badges/badges.dart';
import 'package:hospital/BestDeatProducts/best_deal_product_page.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/FirstSection/carousel.dart';
import 'package:hospital/Drawer/drawercontent.dart';
import 'package:hospital/FloatingActionButton/ConsultWithDoctor/consult_with_doctor.dart';
import 'package:hospital/MedicineCateory/medicine_category_page.dart';
import 'package:hospital/SecondSection/second_page.dart';

import 'package:hospital/ThirdSection/third_page.dart';
import 'package:hospital/TrendingProducts/trending_product_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'No Internet/connectivity_provider.dart';
import 'No Internet/no_internet.dart';
import 'package:http/http.dart' as http;

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

class _HomePageState extends State<HomePage> {
  SharedPreferences loginData;
  // late String username;

  Future getUsername() async {
    loginData = await SharedPreferences.getInstance();
    setState(() {
      // print("uname" + uname.toString());
      print("dddpppuu1 : responceData_un" +
          loginData.getString('responceData_un').toString());
      print("dddpppuu2 : responceData_ue" +
          loginData.getString('responceData_ue').toString());
      print("dddpppuu3 : responceData_status" +
          loginData.getString('responceData_status').toString());
      String responceData_uid =
          loginData.getString('responceData_uid').toString();
    
      fetchData(responceData_uid);
    });
  }

  var response;

  var addToCartApi;

  @override
  void initState() {
    // TODO: implement initState
    //
    super.initState();

    Provider.of<ConnectivityProvider>(context, listen: false).startMonitering();
// for loading
    getUsername();
  }

  fetchData(String argResponceData_uid) async {
    var api = Uri.parse(
        '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${argResponceData_uid}');
    print('cartpage' + api.toString());

    response = await http.get(api);

    print("Carousel" + response.body);

    addToCartApi = jsonDecode(response.body);
    print('addToCartApi' + addToCartApi['total'].toString());

    print('totalPriceAfterOffer' + totalPriceAfterOffer.toString());

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: kGreen,
          title: Text(
            "BK Arogyam",
            style: TextStyle(fontStyle: FontStyle.italic),
          ),
          actions: [
            
            response != null
                ? Badge(
                    position: BadgePosition.topEnd(top: 3, end: 18),
                    animationDuration: Duration(milliseconds: 300),
                    animationType: BadgeAnimationType.slide,
                    badgeContent: Text(
                      addToCartApi['total']['num'].toString(),
                      style: TextStyle(color: Colors.white),
                    ),
                    child: IconButton(
                        icon: Icon(Icons.shopping_cart),
                        padding: EdgeInsets.only(right: 30.0),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => Cartpage()),
                          );
                        }),
                  )
                : IconButton(
                    icon: Icon(Icons.shopping_cart),
                    // onPressed: () => print("open cart"),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Cartpage()),
                      );
                    },
                  ),
            DropDownMenu(),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: kGreen,
          onPressed: () => Navigator.push(context,
              MaterialPageRoute(builder: (context) => ConsultWithDoctor())),
          tooltip: 'Consult With Doctor',
          child: Container(
            child: Image(
              image: AssetImage(
                "assets/icons/cwd.png",
              ),
              color: Colors.white,
              width: 40,
              height: 40,
            ),
          ),
        ),
        drawer: Drawer(
          child: DrawerContent(),
        ),
        body: pageUI());
  }

  Widget pageUI() {
    return Consumer<ConnectivityProvider>(
      builder: (consumerContext, model, child) {
        if (model.isOnline != null) {
          return model.isOnline
              ? ListView(
                  children: [
                    Carousel(),
                    SizedBox(
                      height: 10.0,
                    ),
                    MedicineCategoryPage(),
                    SizedBox(
                      height: 10.0,
                    ),
                    SecondPage(),
                    SizedBox(
                      height: 10.0,
                    ),
                    ThirdPage(),
                    SizedBox(
                      height: 10.0,
                    ),
                    TrendingProductPage(),
                    SizedBox(
                      height: 16.0,
                    ),
                    BestDealProductPage(),
                    SizedBox(
                      height: 10.0,
                    ),
                  ],
                )
              : NoInternet();
        }
        return Container(
          child: Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    );
  }
}
6bc51xsx

6bc51xsx1#

您可以使用provider包提供的更改通知程序。
并观看如何使用的视频,正是为您的用例搜索YouTube更改通知提供商由不断增长的开发人员
希望能有所帮助🙂

olmpazwi

olmpazwi2#

您可以使用提供程序(提供程序:^5.0.0)或Getx(获取:^4.1.4)来处理这种情况。有很多例子可以用于GetX和Provider。
如果您不想使用其中任何一个,则将您的购物车/工卡计数存储到tempCartCount变量(例如:int cartCount = 0),并将其设置为工卡计数,而不是“addToCartApi ['total']['num'].toString()”,确保在更新/添加购物车项目时设置状态。
这里我提供了一个简单的例子,说明如何更新appBar上的count。
如果要将任何其他屏幕标记cartCount更改为全局,或者可以将其设置为本地/专用。

import 'package:badges/badges.dart';
import 'package:flutter/material.dart';

class UpdateCountExample extends StatefulWidget {
  @override
  _UpdateCountExampleState createState() => _UpdateCountExampleState();
}

int cartCount = 0;

class _UpdateCountExampleState extends State<UpdateCountExample> {
  List<String> cartArray = [];

  @override
  void initState() {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      setState(() {
        cartCount = 0;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("App Bar"),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 18.0, top: 5.0),
            child: Badge(
              badgeContent: Text(cartCount.toString()),
              child: Icon(Icons.add_shopping_cart),
            ),
          )
        ],
      ),
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "Add item in cart",
              textAlign: TextAlign.center,
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, decoration: TextDecoration.none, color: Colors.black),
            ),
            SizedBox(
              height: 20,
            ),
            InkWell(
              onTap: () {
                setState(() {
                  cartArray.add("value ${cartArray.length}");
                  cartCount = cartArray.length;
                });
              },
              child: Container(
                padding: const EdgeInsets.all(10.0),
                color: Colors.amber,
                child: Text(
                  "Add Item",
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 15, decoration: TextDecoration.none, color: Colors.black),
                ),
              ),
            ),
            Expanded(
              child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: cartArray.length,
                  itemBuilder: (context, index) {
                    return Text(
                      cartArray[index],
                      style: TextStyle(fontSize: 20, color: Colors.black),
                    );
                  }),
            )
          ],
        ),
      ),
    );
  }
}
u0sqgete

u0sqgete3#

我已经使用StreamBuilder即时更新购物车项目。
你可以使用这篇文章中的代码如何在flutter中使用Streambuilder

相关问题