【问题标题】:price from each item from listview into Total price is runing more than once,which is not the correct . How to run it once从列表视图到总价的每个项目的价格运行不止一次,这是不正确的。如何运行一次
【发布时间】:2020-05-13 07:30:27
【问题描述】:

我的 listview 总价格代码运行不止一次,这再次添加到价格变量中,这不是正确的值,如何防止它运行两次。根据我的研究,我未来的构建者是构建方法,如果这是问题,那么如何去做,或者任何其他建议都会很棒。

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    每次构建方法运行时,您都可以求和并添加值。您可以每次重置 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));
    

    【讨论】:

    • 根据您的建议,我在每次调用该函数时都重置该值,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 2019-06-09
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多