【问题标题】:Deleting an item from ListView.builder in Flutter在 Flutter 中从 ListView.builder 中删除一个项目
【发布时间】:2022-01-23 12:50:21
【问题描述】:

我正在尝试实现一个功能,在用户确认删除(“是”按钮和“否”按钮)后,长按从列表中删除所选项目。我正在使用 Inkwell。

我尝试了几种不同的方法,但找不到任何东西。

我发现了一篇类似的帖子,但没用。

注意:我不想使用 Dismissable

这里是代码:-

import 'package:flutter/material.dart';
import 'package:smoorapplication/src/services/api.dart';
import 'package:percent_indicator/percent_indicator.dart';

class BodyFunctionCard extends StatefulWidget{
  const BodyFunctionCard({Key key}) : super(key: key);
  @override
  _BodyFunctionCardHPState createState() => _BodyFunctionCardHPState();
}

class _BodyFunctionCardHPState extends State<BodyFunctionCard>{
  List<bool> isExpanded = List.generate(100, (index) => false);
  List<bool> isAccepted = List.generate(100,(index) => false);
  List<bool> isPicked = List.generate(100,(index) => false);
  List<bool> isArrived = List.generate(100,(index) => false);
  List<bool> isDelRet = List.generate(100,(index) => false);
  List<bool> isFinished = List.generate(100,(index) => false);
  List<bool> countfin = List.generate(100,(index) => false);
  List<double> lpind = List.generate(100, (index) => 0.0);
  @override
  Widget build(BuildContext context){
    return Card(
        child: FutureBuilder(
          future: apiGetOrder(),
          builder: (BuildContext context, AsyncSnapshot snapshot){
              if(snapshot.connectionState == ConnectionState.none || snapshot.hasData == null){
                return const Center(child:
                Text('Loading data . . . !'),);
              }return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                return Column(
                  children: <Widget>[
                    InkWell(child:
                    Container(
                      height: 200,
                      width: 380,
                      margin: const EdgeInsets.all(0.0),
                      decoration: BoxDecoration(
                        border: Border.all(width: 1.5, color: Colors.grey),
                      ),
                      child: Column(children: <Widget>[
                        const SizedBox(height: 3.5,),
                        Container(
                          height: 30,
                          width: 370,
                          color: const Color.fromRGBO(220,220,220,2.0),
                          child: Row(children: <Widget>[
                            Text('  ${snapshot.data[index].orderNumber}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),),
                            const SizedBox(width: 130,),
                            LinearPercentIndicator(
                              width: 100,
                              lineHeight: 15,
                              percent: lpind[index],
                              backgroundColor: Colors.orange,
                              progressColor: Colors.lightGreen,
                            ),
                            const SizedBox(width: 10,),
                            Text('  ${snapshot.data[index].orderNumber}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),)
                          ],),
                        ),
                        const SizedBox(height: 10,),
                        Row(children: <Widget>[
                          RichText(text: const TextSpan(
                              children: [
                                WidgetSpan(
                                    child: Padding(padding: EdgeInsets.symmetric(horizontal: 10.0),child: Icon(Icons.circle, color: Colors.orange, size: 18,),)
                                )
                              ]
                          )),
                          const Text('PICKUP LOCATION', style: TextStyle(fontSize: 16),)
                        ],),
                        const SizedBox(height: 5,),
                        Row(children: <Widget>[
                          Text('        ${snapshot.data[index].lineItems[0].originLocation.name} ${snapshot.data[index].lineItems[0].originLocation.address1}',
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                          )
                        ],),
                        Row(children: <Widget>[
                          Text('        ${snapshot.data[index].lineItems[0].originLocation.address2}',
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                          )
                        ],),
                        const SizedBox(height: 10,),
                        Row(children: <Widget>[
                          RichText(text: const TextSpan(
                              children: [
                                WidgetSpan(
                                    child: Padding(padding: EdgeInsets.symmetric(horizontal: 10.0),child: Icon(Icons.circle, color: Colors.lightGreen, size: 18,),)
                                )
                              ]
                          )),
                          const Text('DELIVERY LOCATION', style: TextStyle(fontSize: 16),)
                        ],),
                        const SizedBox(height: 5,),
                        Row(children: <Widget>[
                          Text('        ${snapshot.data[index].lineItems[0].originLocation.name} ${snapshot.data[index].lineItems[0].originLocation.address1}',
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                          )
                        ],),
                        Row(children: <Widget>[
                          Text('        ${snapshot.data[index].lineItems[0].originLocation.address2}',
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                          )
                        ],)
                      ],),
                    ),
                      onTap: (){
                        setState(() {
                          isExpanded[index] = !isExpanded[index];
                        });
                      },
                      onLongPress: (){
                        setState(() {
                          // I want to delete the item at the current index.
                        });
                      },
                    ),
                    const SizedBox(height: 10,),
                  ],
                );
            }
          );
        }
      ),
    );
  }
}

我是 Flutter 的新手,有知识我会帮助别人的。

【问题讨论】:

    标签: android flutter dart user-interface flutter-layout


    【解决方案1】:

    第 1 步:查找特定对象(元素)VIA 的索引

    Your_List_Name.indexOf(Your_List_Name[index]);
    
    ex:_userData.indexOf(_userData[index]) 
    

    第 2 步:删除特定索引处的对象

    Your_LIST_Name.removeAt(index);
    
    ex: _userData.removeAt(index);
    

    根据您的代码数据是您的列表名称

    【讨论】:

    【解决方案2】:

    你试过了吗?

    yourList.remove(index);
    

    yourList.removerWhere(()=> yourSnapshotData == theSnaspshotData);
    

    【讨论】:

    • 我不知道我的列表名称是什么。你能告诉我我的代码吗?
    【解决方案3】:

    这是一个简单的例子

    class MyHomePage extends StatefulWidget {
      final String title;
    
      const MyHomePage({
        Key? key,
        required this.title,
      }) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      List items = [
        {"name": "item one", "color": Colors.red},
        {"name": "item two", "color": Colors.blue},
        {"name": "item three", "color": Colors.yellow},
        {"name": "item four", "color": Colors.pink},
      ];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              return InkWell(
                  onLongPress: () {
                    showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                              title: Text("DELETE?"),
                              actions: [
                                IconButton(
                                    icon: Icon(Icons.check),
                                    onPressed: () {
                                      items.removeAt(index);
                                      setState(() {});
                                      Navigator.pop(context);
                                    })
                              ],
                            ));
                  },
                  child: Container(
                      height: 50,
                      child: Text(items[index]['name']),
                      color: items[index]['color']));
            },
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案4】:

      我相信你有两个问题:

      1. 关于长按选项的按钮。为此,您可以使用RawMaterialButton。下面是示例。
      child: RawMaterialButton(
        onPressed: (){},   // if you want an action on single press, you can write here
        onLongPress: () => _confirmationBox(snapshot.data[index]), // call a function on long press
      ),
      
      1. 您想显示一个确认框。为此,您可以使用showDialog。请参见下面的示例。
      void _confirmationBox(BuildContext context) {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('Are you sure?'),
              content: const Text('On pressing OK it will get deleted'),
              actions: [
                SizedBox(
                  height: 50,
                  child: TextButton(
                    onPressed: (){
                      snapshot.data.removeAt(index);
                    },
                    child: const Text(
                      'Ok',
                    ),
                  ),
                ),
                SizedBox(
                  height: 50,
                  child: TextButton(
                    onPressed: (){},
                    child: const Text(
                      'Cancel',
                    ),
                  ),
                ),
              ],
            ),
          );
        }
      

      注意:更好的方法是使用数据的 id 将其从列表中删除,而不是使用索引值。

      【讨论】:

        猜你喜欢
        • 2021-01-19
        • 2022-08-05
        • 2020-11-10
        • 2021-06-28
        • 2021-12-26
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 2022-11-22
        相关资源
        最近更新 更多