Flutter: Displaying total sum of items

so I was making a cart page for my ecommerce app and I want to Display total sum of items at the bottom of the scaffold . But the problem is even after using state management it is not giving me the expected result.

this is my total value controller.

 class totalvaluecontroller extends GetxController {
  RxInt  total = 0.obs;}

This is the code to fetch every item id for the user

class appcart extends StatefulWidget {
  appcart({Key? key}) : super(key: key);

  @override
  _appcartState createState() => _appcartState();
}

class _appcartState extends State<appcart> {
  @override
  Widget build(BuildContext context) {
    //bool all_items = false;
    totalvaluecontroller valuecontroller = Get.find();
    FirebaseController controller = Get.find();
    String custom_uid = controller.firebaseUser.value!.uid;
    return Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text(
              "Your Cart",
            ),
            backgroundColor: Colors.black87,
            leading: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {
                  Get.back();
                }),
            actions: [],
          ),
          body: Padding(
            padding: const EdgeInsets.symmetric(
                horizontal: 20.0, vertical: 20.0),
            child: StreamBuilder<DocumentSnapshot>(
              stream: FirebaseFirestore.instance
                  .collection("User_Carts")
                  .doc(custom_uid)
                  .snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<DocumentSnapshot>
                      snapshot) {
                if (snapshot.hasError) {
                  return Text("Error: ${snapshot.error}");
                }
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return SpinKitFadingCircle(
                        color: Colors.black45);
                  default:
                    return new ListView.builder(
                      itemCount:
                          snapshot.data!['Items'].length,
                      itemBuilder: (BuildContext context,
                          int index) {
                        return itemtile(
                          productid: snapshot.data!['Items']
                              [index],
                          custom_uid: custom_uid,
                          index: index,
                        );
                      },
                    );
                }
              },
            ),
          ),
          bottomNavigationBar:
              BottomAppBar(child: totaldisplaer()),  //THE MAIN PROBLEM
        );
  }
}

This is the code to fetch info about every product and displaying in a card

class itemtile extends StatelessWidget {
  final String productid;
  final String custom_uid;
  final int index;
  const itemtile(
      {required this.productid,
      required this.custom_uid,
      required this.index});

  @override
  Widget build(BuildContext context) {
    totalvaluecontroller valuecontroller = Get.find();
    return StreamBuilder<DocumentSnapshot>(
        stream: FirebaseFirestore.instance
            .collection("Products")
            .doc(productid.trim())
            .snapshots(),
        builder: (BuildContext context,
            AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          /*else if (!snapshot.hasData) {
            return CircularProgressIndicator();
          }*/
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return SpinKitFadingCircle(
                  color: Colors.black45);
            default:
              valuecontroller.total =
                  valuecontroller.total +
                      (snapshot.data!["Price"] as int);
            
              return Card(
                elevation: 20.0,
                color: Color(snapshot.data!['Colour']),
                shape: RoundedRectangleBorder(
                    borderRadius:
                        BorderRadius.circular(15.0)),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: <Widget>[
                      Container(
                        height: 50.0,
                        width: 50.0,
                        child: CachedNetworkImage(
                          placeholder: (context, url) =>
                              Center(
                                  child: SpinKitWave(
                            color: Colors.white38,
                          )),
                          imageUrl: snapshot.data!['Url'],
                        ),
                      ),
                      SizedBox(
                        width: 10.0,
                      ),
                      Text(snapshot.data?['Brand']),
                      Spacer(),
                      Column(
                        children: <Widget>[
                          SizedBox(height: 25),
                          Text(
                              "\$${snapshot.data?['Price']}"),
                        ],
                      )
                    ],
                  ),
                ),
              );
          }
        });
  }
}

now since I want to display sum in bottom used a bottom navigation bar and used this code

class totaldisplaer extends StatelessWidget {
  const totaldisplaer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    totalvaluecontroller valuecontroller = Get.find();

    return Obx(() => Text("${valuecontroller.total}"));
  }
}

Gives me following error

enter image description here

Please suggest a solution



Read more here: https://stackoverflow.com/questions/68468341/flutter-displaying-total-sum-of-items

Content Attribution

This content was originally published by Daksh Gupta at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: