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 如何在Flatter中手动向listview添加项目_Flutter_Dart - Fatal编程技术网

Flutter 如何在Flatter中手动向listview添加项目

Flutter 如何在Flatter中手动向listview添加项目,flutter,dart,Flutter,Dart,我有一个购物车项目列表,我正在使用下面的代码显示。在这个列表之后,我想显示总金额。最终结果应该是这样的: 鸡肉汉堡1X$20.5 鸡肉卷1X$9.99 总额30.49美元 Container( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4), height: min(widget.order.products.length * 20.0 + 10, 100),

我有一个购物车项目列表,我正在使用下面的代码显示。在这个列表之后,我想显示总金额。最终结果应该是这样的:

鸡肉汉堡1X$20.5
鸡肉卷1X$9.99
总额30.49美元

Container(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
            height: min(widget.order.products.length * 20.0 + 10, 100),
            child: ListView(
              children: widget.order.products
                  .map(
                    (prod) => Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                             Expanded(child:Text(
                              prod.title,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            )),
                           Text(
                              '${prod.quantity}x \$. ${prod.price}',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey,
                              ),
                            )
                          ],          
                        ),
                  )
                  .toList(), 
容器(
填充:边缘组。对称(水平:15,垂直:4),
高度:最小值(widget.order.products.length*20.0+10100),
子:ListView(
子项:widget.order.products
.地图(
(prod)=>行(
mainAxisAlignment:mainAxisAlignment.spaceBetween,
儿童:[
扩展(子:文本)(
产品名称,
样式:TextStyle(
尺寸:16,
fontWeight:fontWeight.bold,
),
)),
正文(
“${prod.quantity}x\$.${prod.price}”,
样式:TextStyle(
尺寸:16,
颜色:颜色。灰色,
),
)
],          
),
)
.toList(),

如何将总计添加到此列表?

op更新评论中的更多信息后,编辑1:

Column(children: [  Text(widget.order.totalPrice.toString()),
Flexible(child:
ListView(
children: 
  widget.order.products
 .map((prod) => Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, 
  children: <Widget>[
  Expanded(child:Text(
  prod.title,
  style: TextStyle(
  fontSize: 16,
  fontWeight: FontWeight.bold,
   ),
  )),
 Text(
 '${prod.quantity}x \$. ${prod.price}',
   style: TextStyle(
     fontSize: 16,
   color: Colors.grey,
    ),
   )
  ],          
 ),
)
.toList())]), 

无论您想在何处显示此
totalPrice
,但您不能将其显示在列表视图中。

编辑1,op更新评论中的更多信息后:

Column(children: [  Text(widget.order.totalPrice.toString()),
Flexible(child:
ListView(
children: 
  widget.order.products
 .map((prod) => Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, 
  children: <Widget>[
  Expanded(child:Text(
  prod.title,
  style: TextStyle(
  fontSize: 16,
  fontWeight: FontWeight.bold,
   ),
  )),
 Text(
 '${prod.quantity}x \$. ${prod.price}',
   style: TextStyle(
     fontSize: 16,
   color: Colors.grey,
    ),
   )
  ],          
 ),
)
.toList())]), 

无论您想在哪里显示此
totalPrice
,您都不能将其显示在listView中。

如果您想向listView添加项目,首先必须将这些项目添加到您的列表中(例如order.products或new one),然后使用状态管理方法重新呈现listView。如果您的逻辑很简单,您可以使用有状态小部件

示例代码:

类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
家:脚手架(
正文:MyList(),
),
);
}
}
类MyList扩展了StatefulWidget{
@凌驾
_MyListState createState();
}
类_MyListState扩展状态{
列出订单=[“订单1”、“订单2”、“订单3”];
@凌驾
小部件构建(构建上下文){
返回列(
儿童:[
扩大(
子:ListView(
儿童:命令
.地图(
(字符串e)=>卡(
孩子:ListTile(
标题:文本(e),
),
),
)
.toList(),
),
),
文本按钮(
已按下:(){
列出外部字段=[“字段1”、“字段2”];
设定状态(
() {
orders.addAll(外部字段);
},
);
},
子项:文本(“添加额外字段”),
),
],
);
}
}

如果要将项目添加到ListView,首先必须将这些项目添加到列表中(例如order.products或new one),然后使用状态管理方法重新呈现ListView。如果逻辑简单,则可以使用有状态小部件

示例代码:

类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
家:脚手架(
正文:MyList(),
),
);
}
}
类MyList扩展了StatefulWidget{
@凌驾
_MyListState createState();
}
类_MyListState扩展状态{
列出订单=[“订单1”、“订单2”、“订单3”];
@凌驾
小部件构建(构建上下文){
返回列(
儿童:[
扩大(
子:ListView(
儿童:命令
.地图(
(字符串e)=>卡(
孩子:ListTile(
标题:文本(e),
),
),
)
.toList(),
),
),
文本按钮(
已按下:(){
列出外部字段=[“字段1”、“字段2”];
设定状态(
() {
orders.addAll(外部字段);
},
);
},
子项:文本(“添加额外字段”),
),
],
);
}
}

为此,您必须学习。为了使事情变得简单,我们将使用内置提供数据。将ui与业务逻辑分离是最佳做法,因此我将在这里进行介绍

为了使用
StreamBuilder
,您必须为它提供一个
Stream
,其中
T
是变量的类型。在您的情况下,它是一个
列表
。让我们将其写入另一个保存所有业务逻辑的文件中

product\u-bloc.dart

class ProductBloc {
  final List<String> _productList = ["Item One", "Item Two"];
  StreamController<List<String>> _products = StreamController<List<String>>();
  Stream<List<String>> get products => _products.stream;

  ProductBloc() {
    _products.add(_productList);
  }

  void addProductAfterDelay() async {
    _productList.add("Item Three");
    await Future.delayed(const Duration(seconds: 3));
    _products.add(_productList);
  }
}
StreamBuilder<List<String>>(
  initialData: [],
  builder: (context, snapshot) {
    return ListView.builder(
      itemCount: snapshot.data.length,
      itemBuilder: (context, index) {
      return Text(snapshot.data[index]);
    });
  },
);

为此,您必须学习。为了使事情变得简单,我们将使用内置功能来提供数据。将ui与业务逻辑分离是最佳做法,因此我将在这里进行介绍

为了使用
StreamBuilder
,您必须为它提供一个
Stream
,其中
T
是变量的类型。在您的情况下,它是一个
列表
。让我们将其写入另一个保存所有业务逻辑的文件中

product\u-bloc.dart

class ProductBloc {
  final List<String> _productList = ["Item One", "Item Two"];
  StreamController<List<String>> _products = StreamController<List<String>>();
  Stream<List<String>> get products => _products.stream;

  ProductBloc() {
    _products.add(_productList);
  }

  void addProductAfterDelay() async {
    _productList.add("Item Three");
    await Future.delayed(const Duration(seconds: 3));
    _products.add(_productList);
  }
}
StreamBuilder<List<String>>(
  initialData: [],
  builder: (context, snapshot) {
    return ListView.builder(
      itemCount: snapshot.data.length,
      itemBuilder: (context, index) {
      return Text(snapshot.data[index]);
    });
  },
);

这是我的建议。

我使用spread操作符向ListView的子项添加与“total”相关的小部件。

此外,由于ListView中的项目总数,我在容器高度添加了一个项目。
下面是我做的总结代码

ListView(
    children: <Widget> [
        ...list.map(...).toList(),
        TotalWidget(),
    ]
)
ListView(
儿童:[
…list.map(…).toList(),
TotalWidget(),
]
)
这是基于您的代码的完整代码

import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showModalBottomSheet(
            context: context,
            backgroundColor: Colors.blueGrey,
            isScrollControlled: false,
            builder: (context) => Wrap(
              children: [
                ListView.separated(
                  shrinkWrap: true,
                  itemCount: 3,
                  itemBuilder: (BuildContext context, int index) => ListTile(
                    title: Text(
                      'lists[index].listName',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                  separatorBuilder: (BuildContext context, int index) =>
                      Divider(),
                ),
              ],
            ),
          );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildBody() {
    List<Product> listProduct = [
      Product('Chicken Burger', 1, 20.5),
      Product('Chicken Wrap', 1, 9.99),
    ];
    double totalAmount = 0;
    for (var item in listProduct) {
      totalAmount += (item.price * item.quantity);
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
      height: min((listProduct.length + 1) * 20.0 + 10, 100),
      child: ListView(
        children: [
          ...listProduct
              .map(
                (prod) => Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      prod.title,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    )),
                    Text(
                      '${prod.quantity}x \$. ${prod.price}',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey,
                      ),
                    )
                  ],
                ),
              )
              .toList(),
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Expanded(
                    child: Text(
                  'Total',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                )),
                Text(
                  '$totalAmount',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey,
                  ),
                )
              ])
        ],
      ),
    );
  }
}

class Product {
  String title;
  int quantity;
  double price;

  Product(this.title, this.quantity, this.price);
}
导入