I want to display the total price on the button like this "buy now $15" $15 is the total price, now I'm confused about how to do it, I've tried it but the results are not what I want.
this my code
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)),
),
],
),
],
),
),
],
);
}
}
I want when adding a product then the price is updated to the total price and retrieved in the button. there is 1 way that works but when I want to display the price to the button by calling the totalPrice variable it always fails.
In CartController create a variable as
RxInt totalPrice=0.obs;
On press to add to card button do:
cartController.totalPrice.value += itemPrice
Then where you want to show to total price just wrap that with GetX Widget as
GetX<CartController>(
builder: (controller){
return Text("Total Price: controller.totalPrice.value;});
As you are using getx widget what will it do it will rebuild the text widget when ever there is the change in value to total Price.