从小部件列表中删除小部件[Flutter]

问题描述

在我正在构建的Flutter应用程序中(基本上是一个待办事项列表),我希望使用一个按钮删除所有已完成的任务(活动复选框)。 到目前为止,只有在最后一个复选框处于活动状态并且所有其他活动复选框(如果有)都在其上方时,它才能按预期运行。

如果一个活动复选框之后甚至有1个非活动复选框,则该应用程序也会发生故障。

这是创建任务小部件的类的代码

Scala <-> C lib
Scala <-> Rust lib

这是删除任务小部件的func的代码

class addnote extends StatefulWidget {

  final String task_txt;
  final int index;// receives the value

  addnote({ Key key,this.task_txt,this.index }): super(key: key);

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

class _addnoteState extends State<addnote> {

  bool value=false;
  
  Widget txt_strike(String to_strike,bool str_value){
    return str_value ?
    AutoSizeText(to_strike,style: TextStyle(
      decoration: Textdecoration.lineThrough,fontFamily: "Quicksand",fontSize: 20.0,color: Colors.grey,),maxLines: 2,overflow: TextOverflow.ellipsis,)
        :
    AutoSizeText(to_strike,style: TextStyle(
      //decoration: Textdecoration.lineThrough,color: Colors.black,);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Boxdecoration(
        borderRadius:BorderRadius.circular(4.0),BoxShadow: [BoxShadow(
        color:Colors.grey,offset: Offset(-6.0,4.0),blurRadius: 4.0,)],color: Colors.white
        ),margin: EdgeInsets.symmetric(vertical: 5.0,horizontal: 3.0),child:InkWell(

        onTap: (){setState(() {
          value=!value;
          w_checks[widget.index]=!w_checks[widget.index];
        });},child: Row(
          mainAxisAlignment: MainAxisAlignment.start,children: [
            Expanded(flex:1,child: CircularCheckBox(
                  disabledColor: Colors.white,activeColor: Colors.green,value: value,onChanged:(bool _changed)
                  {
                    // print(w_checks[Index]);
                    setState(() {
                      value=!value;
                      w_checks[widget.index]=!w_checks[widget.index];
                    });
                  }),Expanded(flex:5,child: txt_strike(widget.task_txt,value)),],)
    );
  }
}

希望我能描述我的问题,请帮忙。

解决方法

我不太确定您在del_task()内部正在做什么,但是我认为您的问题是由for循环引起的,在该循环中,您将所有以后的对象向下移动一个位置。

该操作已经由“ list.removeAt(index)”方法执行,如您从文档中看到的:https://api.dart.dev/stable/2.10.2/dart-core/List/removeAt.html

我会这样更改代码:

void del_task(){
   for(int i=0; i<w_checks.length; i++)
   {
       if(w_checks[i]==true)
       {
         setState(() {
           w_tasks.removeAt(i);  
           w_checks.removeAt(i);   
         });
         i--;
       }
   }
 }

我不明白您为什么需要count变量。

我发布的代码应遍历w_checks。 当发现“真”值时,它将调用removeAt(i),然后将索引减1。