Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 从listview到Total price的每个项目的价格运行不止一次,这是不正确的。如何运行一次_Flutter_Dart - Fatal编程技术网

Flutter 从listview到Total price的每个项目的价格运行不止一次,这是不正确的。如何运行一次

Flutter 从listview到Total price的每个项目的价格运行不止一次,这是不正确的。如何运行一次,flutter,dart,Flutter,Dart,我的listview total price代码运行不止一次,它再次添加到price变量中,这不是正确的值,如何防止它运行两次。根据我的研究,我未来的建设者是在构建方法,如果这是一个问题,那么如何做到这一点,或任何其他建议将是伟大的 import 'package:flutter/material.dart'; import 'package:restaurant_ui_kit/models/user.dart'; import 'package:restaurant_ui_kit/screen

我的listview total price代码运行不止一次,它再次添加到price变量中,这不是正确的值,如何防止它运行两次。根据我的研究,我未来的建设者是在构建方法,如果这是一个问题,那么如何做到这一点,或任何其他建议将是伟大的

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,
    ),
  );
}

每次运行生成方法时,都要求和并添加值。您可以每次重置小计,或者有一种较短的方法对值求和,您可以尝试;而不是使用

for (int i = 0; i < snapshot.data.length; i++) {
  subTotal = subTotal +
      int.parse(
          User.fromMap(snapshot.data[position]).price);
}

根据您的建议,每次调用函数时,我都会重置该值,并且它工作正常,谢谢。
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));