flutter - 购物车屏幕和总价

问题描述 投票:0回答:0

我想在按钮上显示总价,例如“立即购买 $15” $15 是总价,现在我很困惑该怎么做,我试过了,但结果不是我想要的。

这是我的代码

class CartPage extends StatelessWidget {
  Future _fetchdata() async {
    try {
      final response = await http.get(Uri.parse(url + 'product'),
          headers: {'Accept': 'application/json'});
      if (response.statusCode == 200) {
        return jsonDecode(response.body)[0]['data'];
      }
    } catch (e) {
      print(e.toString());
    }
  }

  final cartController = Get.put(CartController());
  // final CartItem item;
  CartPage({super.key});
  @override
  Widget build(BuildContext context) {
    _fetchdata();
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10, top: 25),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: 15),
              Text(
                "Menu Food XYZ",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800),
              ),
              SizedBox(height: 13),
              Container(
                margin: EdgeInsets.only(top: 10),
                // color: Colors.grey,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(10),
                ),
                child: TextField(
                  decoration: InputDecoration(
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 15),
                    hintText: 'Search',
                    suffixIcon: Icon(Icons.search),
                    border: InputBorder.none,
                  ),
                ),
              ),
              SizedBox(height: 12),
              Text(
                "Semua",
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 19,
                ),
              ),
              SizedBox(height: 12),
              FutureBuilder(
                future: _fetchdata(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  } else {
                    return ListView.builder(
                      physics: BouncingScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, index) {
                        if (snapshot.hasData) {
                          return CartItem(
                              nama: snapshot.data[index]['nama'],
                              harga: snapshot.data[index]['harga'],
                              gambar: snapshot.data[index]['gambar'],
                              rating: snapshot.data[index]['rating']);
                        } else {
                          return Text("data not oke!");
                        }
                      },
                    );
                  }
                },
              ),
              Container(
                margin: EdgeInsets.only(top: 10, bottom: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () async {
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const InvoicePage(),
                          ),
                        );
                      },
                      child: Text("Buy Now " + cartController.GetTotalPrice().toString()),
                      style: ElevatedButton.styleFrom(
                        padding:
                            EdgeInsets.symmetric(horizontal: 35, vertical: 16),
                        backgroundColor: Colors.blue.shade600,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}






// ignore: must_be_immutable
class CartItem extends StatefulWidget {
  CartItem({
    super.key,
    required this.nama,
    required this.harga,
    required this.gambar,
    required this.rating,
  });
  String nama, gambar, rating;
  int harga;
  // int product;
  @override
  State<CartItem> createState() => _CartItemState();
}

class _CartItemState extends State<CartItem> {
  var product = 0;
  final cartController = Get.put(CartController());
  final formatter =
      NumberFormat.currency(locale: 'id-ID', symbol: 'Rp', decimalDigits: 0);
  @override
  Widget build(BuildContext context) {
    int totalPrice = widget.harga * product;
    return Column(
      children: [
        Container(
          color: Colors.white,
          margin: EdgeInsets.symmetric(vertical: 10),
          child: Row(
            children: <Widget>[
              Container(
                width: 80,
                height: 100,
                padding: EdgeInsets.all(3),
                child: Center(
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.red[100],
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: NetworkImage(widget.gambar),
                      ),
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                ),
              ),
              SizedBox(
                width: 12,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 200,
                    child: Text(
                      widget.nama,
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
                    ),
                  ),
                  SizedBox(
                    height: 3,
                  ),
                  Text(totalPrice.toString()),
                  Container(
                    width: 100,
                    child: Text(
                      formatter.format(widget.harga),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Row(
                    children: [
                      Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                            color: Colors.grey[300],
                            borderRadius: BorderRadius.circular(4)),
                        child: ElevatedButton(
                          onPressed: () {
                            setState(() {
                              if (product > 1) {
                                product--;
                              } else {
                                Get.snackbar('Warning', 'Quantity not valid',
                                    backgroundColor: Colors.yellow[500],
                                    colorText: Colors.black);
                              }
                            });
                          },
                          child: Icon(
                            Icons.remove,
                            color: Colors.white,
                            size: 15,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        child: Text(
                          product.toString(),
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: Colors.blue[300],
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: ElevatedButton(
                          onPressed: () {
                            setState(() {
                              product++;
                            });
                          },
                          child: Icon(
                            Icons.add,
                            color: Colors.white,
                            size: 15,
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              ),
              Spacer(),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    child: Text(
                      "⭐ ${widget.rating}",
                      style:
                          TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                    ),
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  Container(
                    width: 30,
                    height: 30,
                    color: Colors.amber[300],
                    child: IconButton(
                        onPressed: () {
                          setState(() {
                            cartController.addToProduct(totalPrice);
                          });
                        },
                        icon: Icon(Icons.add_shopping_cart_sharp)),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }
}

我想在添加产品时将价格更新为总价并在按钮中检索。有一种方法可行,但是当我想通过调用 totalPrice 变量向按钮显示价格时,它总是失败。

flutter dart shopping-cart flutter-getx subtotal
© www.soinside.com 2019 - 2024. All rights reserved.