我的listview总价格代码运行了不止一次,这又又添加到了不正确值的price变量中,如何防止它运行两次。根据我的研究,我的 future 构建者是构建方法,如果这是问题所在,那么该如何做,否则任何其他建议都会很棒。
import 'package:flutter/material.dart';
import 'package:restaurant_ui_kit/models/user.dart';
import 'package:restaurant_ui_kit/screens/checkout.dart';
import 'package:restaurant_ui_kit/util/database_helper.dart';
class CartScreen extends StatefulWidget {
@override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen>
with AutomaticKeepAliveClientMixin<CartScreen> {
var db = new DatabaseHelper();
static int subTotal = 0;
List _users = [];
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Padding(
padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: FutureBuilder<List>(
future: db.getAllUsers(),
initialData: List(),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
final item = snapshot.data[position];
for (int i = 0; i < snapshot.data.length; i++) {
subTotal = subTotal +
int.parse(
User.fromMap(snapshot.data[position]).price);
}
print('toatl is $subTotal');
// get your item data here ...
return Dismissible(
key: UniqueKey(),
child: new Card(
color: Colors.white,
elevation: 2.0,
child: new ListTile(
leading: new CircleAvatar(
child: Text(
"${User.fromMap(snapshot.data[position]).name.substring(0, 1)}"),
),
title: new Text(
"User: ${User.fromMap(snapshot.data[position]).price}"),
subtitle: new Text(
"Id: ${User.fromMap(snapshot.data[position]).id}"),
onTap: () => debugPrint(
"${User.fromMap(snapshot.data[position]).id}"),
),
),
background: slideLeftBackground(),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
final bool res = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
"Are you sure you want to delete ${User.fromMap(snapshot.data[position]).name}?"),
actions: <Widget>[
FlatButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
// TODO: Delete the item from DB etc..
setState(() {
// total();
// print(position);
if (position == 0) {
//print('index 0 dai');
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
//snapshot.data.removeAt(position);
} else {
snapshot.data
.removeAt(--position);
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
}
//print("removed");
// print('mSubTotal $mSubTotal');
});
Navigator.of(context).pop();
},
),
],
);
});
return res;
}
},
);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
),
floatingActionButton: FloatingActionButton(
tooltip: "Checkout",
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Checkout();
},
),
);
},
child: Icon(
Icons.arrow_forward,
),
heroTag: Object(),
),
);
}
@override
bool get wantKeepAlive => true;
}
Widget slideLeftBackground() {
return Container(
color: Colors.red,
child: Align(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Icon(
Icons.delete,
color: Colors.white,
),
Text(
" Delete",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.right,
),
SizedBox(
width: 20,
),
],
),
alignment: Alignment.centerRight,
),
);
}
subTotal在终端中这样打印,正确值是500,因为每件商品的价格为100,并且有5件商品,但是众所周知,最后一个值已分配给变量
I/flutter ( 3885): Count : 5
I/flutter ( 3885): toatl is 500
I/flutter ( 3885): toatl is 1000
I/flutter ( 3885): toatl is 1500
I/flutter ( 3885): toatl is 2000
I/flutter ( 3885): toatl is 2500
最佳答案
每次运行构建方法时,您都要求和并添加值。您可以每次重置subTotal,或者有一种较短的方法来求和,您可以尝试;而不是使用
for (int i = 0; i < snapshot.data.length; i++) {
subTotal = subTotal +
int.parse(
User.fromMap(snapshot.data[position]).price);
}
尝试一下
subTotal = snapshot.data.fold(0, (previousValue, element) => previousValue + int.tryParse(User.fromMap(item).price));
关于flutter - 从 ListView 到总价格的每个项目的价格运行了不止一次,这是不正确的。如何运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61768752/