android - Flutter 在点击索引处更新 onClick 数据

标签 android listview flutter

我正在构建一个食品推车应用程序并在菜单项页面上有一个查询。

我的菜单项页面包含一个 ListView ,其中显示每个项目及其描述以及指定项目数量的选项(1、2、3....)

现在我可以增加或减少单个项目的项目计数,但不确定如何在用户单击的特定索引处的 ListView 中执行此操作。

有人可以帮我解决这个问题吗?

我到目前为止所做的代码如下:

FutureBuilder(
                future: getItemList(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return CircularProgressIndicator();
                  }
                  var itemList = snapshot.data;
                  int itemlength = itemList.length;
                  return ListView.builder(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        height: 100,
                        margin: EdgeInsets.only(left: 10, right: 10, top: 10),
                        decoration: BoxDecoration(
                          color: Colors.white70,
                          border: Border.all(width: 2.0, color: Colors.blueGrey),
                          borderRadius: BorderRadius.circular(6.0),
                          boxShadow: [
                            BoxShadow(
                                color: Color(0xFF6078ea).withOpacity(.3),
                                offset: Offset(0.0, 8.0),
                                blurRadius: 8.0),
                          ],
                        ),
                        child: Row(
                          children: < Widget > [
                            Container(
                              width: 75,
                              child: ClipRRect(
                                borderRadius: new BorderRadius.circular(10.0),
                                child: Image(
                                  image: AssetImage(
                                      'assets/images/loginbg3.jpg'),
                                  fit: BoxFit.cover,
                                ),
                              ),
                              margin: EdgeInsets.only(left: 10),
                            ),
                            Expanded(
                              child: Container(
                                child: Column(
                                  children: < Widget > [
                                    Row(
                                      children: < Widget > [
                                        Expanded(child: Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(itemList[index]['itemname'], style: kClickableTextStyle, ))),
                                        Container(color: Colors.white, width: 25, margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Image.asset(_itemtype)),
                                      ],
                                    ),
                                    Row(
                                      children: < Widget > [
                                        Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text('Price : ', style: kListTitleTextStyle, )),
                                        Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(numberofitems.toString() + ' \u20B9 ', style: kListTitleTextStyle, )),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 10),
                              child: Row(
                                children: < Widget > [
                                  InkWell(
                                    onTap: onClickDelete,
                                    child: Container(
                                      width: 30, child: Icon(
                                      Icons.remove_circle_outline,
                                      color: Colors.green,
                                      size: 30,
                                    ), ),
                                  ),
                                  Container(
                                    width: 30,
                                    child: Center(child: Text(_count.toString(), style: TextStyle(fontSize: 25), )),
                                  ),
                                  InkWell(
                                    onTap: onClickAdd,
                                    child: Container(
                                      margin: EdgeInsets.only(right: 5),
                                      width: 30, child: Icon(
                                      Icons.add_circle_outline,
                                      color: Colors.green,
                                      size: 30,
                                    ), ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                    itemCount: itemList == null ? 0 : itemList.length,
                  );
                })

最佳答案

您可以在下面复制粘贴运行完整代码
第一步:创建Item类
第 2 步:更改 future builder 调用
第 3 步:处理 Inkwell onTap

工作演示

enter image description here

代码 fragment

Future callback;

  @override
  void initState() {
    callback = _getItemList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var futureBuilder =  FutureBuilder(
      future: callback,

...
InkWell(
                      onTap: () {
                        if (itemList[index].numberofitems > 0) {
                          setState(() {
                            itemList[index].numberofitems =
                                itemList[index].numberofitems - 1;
                          });
                        }
                      },

...
InkWell(
                      onTap: () {
                        setState(() {
                          itemList[index].numberofitems =
                              itemList[index].numberofitems + 1;
                          print(
                              ' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
                        });
                      },    

完整代码

import 'dart:async';
import 'dart:collection';

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,
      ),
      home:  MyHomePage(),
    );
  }
}

class Item {
  String itemname;
  String itemtype;
  int numberofitems;

  Item({this.itemname, this.itemtype, this.numberofitems});
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() =>  _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future callback;

  @override
  void initState() {
    callback = _getItemList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var futureBuilder =  FutureBuilder(
      future: callback,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return  Center(child: CircularProgressIndicator());
          default:
            if (snapshot.hasError)
              return  Text('Error: ${snapshot.error}');
            else
              return createListView(context, snapshot);
        }
      },
    );

    return  Scaffold(
      appBar:  AppBar(
        title:  Text("Home Page"),
      ),
      body: futureBuilder,
    );
  }

  Future<List<Item>> _getItemList() async {
    var values =  List<Item>();
    values.add(
        Item(itemname: "A", itemtype: "assets/images/a.jpg", numberofitems: 0));
    values.add(
        Item(itemname: "B", itemtype: "assets/images/a.jpg", numberofitems: 1));
    values.add(
        Item(itemname: "C", itemtype: "assets/images/a.jpg", numberofitems: 2));

    //throw  Exception("Danger Will Robinson!!!");

    await  Future.delayed( Duration(seconds: 2));

    return values;
  }


  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
    List<Item> itemList = snapshot.data;
    return  ListView.builder(
        itemCount: itemList.length,
        itemBuilder: (BuildContext context, int index) {
          {
            return Container(
              height: 100,
              margin: EdgeInsets.only(left: 10, right: 10, top: 10),
              decoration: BoxDecoration(
                color: Colors.white70,
                border: Border.all(width: 2.0, color: Colors.blueGrey),
                borderRadius: BorderRadius.circular(6.0),
                boxShadow: [
                  BoxShadow(
                      color: Color(0xFF6078ea).withOpacity(.3),
                      offset: Offset(0.0, 8.0),
                      blurRadius: 8.0),
                ],
              ),
              child: Row(
                children: <Widget>[
                  Container(
                    width: 75,
                    child: ClipRRect(
                      borderRadius:  BorderRadius.circular(10.0),
                      child: Image(
                        image: AssetImage('assets/images/a.jpg'),
                        fit: BoxFit.cover,
                      ),
                    ),
                    margin: EdgeInsets.only(left: 10),
                  ),
                  Expanded(
                    child: Container(
                      child: Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Expanded(
                                  child: Container(
                                      margin: EdgeInsets.only(
                                          left: 10, top: 15, bottom: 5),
                                      child: Text(
                                        itemList[index].itemname,
                                      ))),
                              Container(
                                  color: Colors.white,
                                  width: 25,
                                  margin: EdgeInsets.only(
                                      left: 10, top: 15, bottom: 5),
                                  child: Image.asset(itemList[index].itemtype)),
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Container(
                                  margin: EdgeInsets.only(
                                      left: 10, top: 15, bottom: 5),
                                  child: Text(
                                    'Price : ',
                                  )),
                              Container(
                                  margin: EdgeInsets.only(
                                      left: 10, top: 15, bottom: 5),
                                  child: Text(
                                    itemList[index].numberofitems.toString() +
                                        ' \u20B9 ',
                                  )),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Row(
                      children: <Widget>[
                        InkWell(
                          onTap: () {
                            if (itemList[index].numberofitems > 0) {
                              setState(() {
                                itemList[index].numberofitems =
                                    itemList[index].numberofitems - 1;
                              });
                            }
                          },
                          child: Container(
                            width: 30,
                            child: Icon(
                              Icons.remove_circle_outline,
                              color: Colors.green,
                              size: 30,
                            ),
                          ),
                        ),
                        Container(
                          width: 30,
                          child: Center(
                              child: Text(
                            itemList[index].numberofitems.toString(),
                            style: TextStyle(fontSize: 25),
                          )),
                        ),
                        InkWell(
                          onTap: () {
                            setState(() {
                              itemList[index].numberofitems =
                                  itemList[index].numberofitems + 1;
                              print(
                                  ' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
                            });
                          },
                          child: Container(
                            margin: EdgeInsets.only(right: 5),
                            width: 30,
                            child: Icon(
                              Icons.add_circle_outline,
                              color: Colors.green,
                              size: 30,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }
          ;
        });
  }
}

关于android - Flutter 在点击索引处更新 onClick 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59450418/

相关文章:

android - 使用 rstdocument 小部件使 kivy 在 android 上崩溃

android - 本地主机在 mac 上运行.. 我可以在我的 Android 手机上查看它吗?

android - onClickItem ListView 自定义 ArrayAdapter Android Studio

java - 在 Fragment 中填充 ListView 时遇到问题

c# - 在 WPF ListView 中将项目显示为图像

flutter 数据表如何在列之间添加垂直边框

Android 动画 recyclerview

android - 应用已在 Google Play 上发布,但无法使用 Google 语音操作

android - flutter - 如何在应用程序启动和使用时下载 Assets

android - IntelliJ IDEA Ultimate Edition(版本2019.3)在Flutter Doctor中显示