Flutter 生成AnimatedBuilder时引发以下RangeError:RangeError(索引):无效值:唯一有效值为0:1

Flutter 生成AnimatedBuilder时引发以下RangeError:RangeError(索引):无效值:唯一有效值为0:1,flutter,Flutter,我试图创建一个列表,在删除和添加项目时可以替换其中的项目和动画,因此我使用了函数隐式ImagedReorderableList,当我试图从列表中删除项目时,它显示了以下错误: ════════ Exception caught by widgets library══════════════════════════════ The following RangeError was thrown building AnimatedBuilder(animation: AnimationContr

我试图创建一个列表,在删除和添加项目时可以替换其中的项目和动画,因此我使用了函数
隐式ImagedReorderableList
,当我试图从列表中删除项目时,它显示了以下错误:

 ════════ Exception caught by widgets library══════════════════════════════
The following RangeError was thrown building AnimatedBuilder(animation: AnimationController#1fbd2(⏮ 0.000; paused)➩_Linear, dirty, state: _AnimatedState#040d2):
RangeError (index): Invalid value: Only valid value is 0: 1

The relevant error-causing widget was: 
  Reorderable-[<'1'>] file:///C:/Users/bentau/Desktop/checkIt/lib/SlideBar/Pages/ToDo.dart:172:26
When the exception was thrown, this was the stack: 
#0      List.[] (dart:core-patch/growable_array.dart:149:60)
#1      _ToDoState.build.<anonymous closure>.<anonymous closure> (package:flutterapp/SlideBar/Pages/ToDo.dart:189:44)
#2      ReorderableState.build.buildChild (package:implicitly_animated_reorderable_list/src/reorderable.dart:123:21)
#3      ReorderableState.build.<anonymous closure> (package:implicitly_animated_reorderable_list/src/reorderable.dart:130:44)
#4      AnimatedBuilder.build (package:flutter/src/widgets/transitions.dart:1012:12)
................................................................................................................
════════ widgets库捕获到异常══════════════════════════════
在构建AnimatedBuilder(动画:AnimationController#1fbd2)时引发以下范围错误(⏮ 0.000;暂停)➩_线性、脏、状态:_AnimatedState#040d2):
RangeError(索引):无效值:只有有效值为0:1
导致错误的相关小部件是:
可重定额-[]file:///C:/Users/bentau/Desktop/checkIt/lib/SlideBar/Pages/ToDo.dart:172:26
引发异常时,这是堆栈:
#0列表。[](dart:core patch/Growtable_阵列。dart:149:60)
#1 _tostate.build。。(套餐:app/SlideBar/Pages/ToDo.省道:189:44)
#2 ReorderableState.build.buildChild(包:隐式\u动画\u reorderable\u列表/src/reorderable.dart:123:21)
#3.ReorderableState.build。(包:隐式\u动画\u可重定向\u列表/src/reorderable.dart:130:44)
#4 AnimatedBuilder.build(包:flatter/src/widgets/transitions.dart:1012:12)
................................................................................................................
这是我的代码:

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/SlideBar/Function/SlideBarMain.dart';
import 'package:flutterapp/SlideBar/Function/ToDoClass.dart';
import 'package:implicitly_animated_reorderable_list/implicitly_animated_reorderable_list.dart';
import 'package:implicitly_animated_reorderable_list/transitions.dart';
class ToDo extends StatefulWidget {
  @override
  _ToDoState createState() => _ToDoState();
}

class _ToDoState extends State<ToDo> {
  final GlobalKey<SlideBarMainState> _key = GlobalKey();
  final GlobalKey <FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<AnimatedListState> listKey = GlobalKey();
  List<ToDoData> restory = [ToDoData(Title: null, Context: null, done: false)];
  List<ToDoData> Data = [
    ToDoData(Title: "Finishing the ToDo", Context: "finish it fast", done: false),
  ];
  int yetdone = 1;
  String title;
  String TodoContext;
//  bool inReorder = false;
//
//  ScrollController scrollController;
//
//  @override
//  void initState() {
//    super.initState();
//    scrollController = ScrollController();
//  }

  void onReorderFinished(List<ToDoData> newItems) {
//    scrollController.jumpTo(scrollController.offset);
    setState(() {
//      inReorder = false;
      Data
        ..clear()
        ..addAll(newItems);
    });
  }
  Widget buildTitle() {
    //create title limiting
    return TextFormField(
      decoration: InputDecoration(labelText: "Title"),
      maxLength: 50, //75
      // ignore: missing_return
      validator: (String value) {
        if (value.isEmpty) {
          return 'Title is Required';
        }
      },
      onSaved: (String value) {
        title = value;
      },
    );
  }

  Widget buildTodoContext() {
    //create the context
    return TextFormField(
      decoration: InputDecoration(labelText: "context"),
      maxLength: 100,
      onSaved: (String value) {
        TodoContext = value;
      },
    );
  }

  createAddFunction(BuildContext context) {
    //new task creator screen
    return showDialog(context: context, builder: (context) {
      return AlertDialog(
          title: Text("Add New ToDo"),
          content: Container(
              margin: EdgeInsets.all(24),
              child: Form(key: formKey, child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  buildTitle(),
                  buildTodoContext(),
                  SizedBox(height: 50,),
                  RaisedButton(
                    child: Text("Save"),
                    onPressed: () {
                      formKey.currentState.save();
                      if (!formKey.currentState.validate()) {
                        return;
                      }
                      else {

                        Data.insert(yetdone, ToDoData(Title: title, Context: TodoContext, done: false,));
                        setState(() {
                          yetdone++;
                        });
                        Navigator.of(context).pop();
                      };
                    },
                  )
                ],
              )
              ))
      );
    });
  }

  Widget DoneBack() {
    //the background when you slide task right
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 20.0),
      color: Colors.green,
      child: const Icon(Icons.done, color: Colors.white,),
    );
  }

  Widget DeleteBack() {
    return Container(
      alignment: Alignment.centerRight,
      padding: EdgeInsets.only(right: 20.0),
      color: Colors.red,
      child: const Icon(Icons.delete, color: Colors.white,),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( // screen background
        backgroundColor: Colors.grey[600],
        appBar: AppBar(
          backgroundColor: Colors.grey[900],
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () => createAddFunction(context),
            ),
          ],
          leading:
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () => _key.currentState.SwitchFunc(),
          ),
          title: Text('ToDo'),
          centerTitle: true,

        ),
        body:
        Stack( // list of tasks
            children: <Widget>[
              ImplicitlyAnimatedReorderableList<ToDoData>(

                items: Data,
                shrinkWrap: true,
                areItemsTheSame: (a, b) => a.Index == b.Index,
                onReorderFinished: (item, from, to, newItems) => onReorderFinished(newItems),
                removeDuration: Duration.zero,
                itemBuilder: (context, itemAnimation, item, index) {
                  return Reorderable(
                    key: ValueKey(index.toString()),
                    builder: (context, dragAnimation, inDrag) {
                      final t = dragAnimation.value;
                      final elevation = lerpDouble(0, 8, t);
                      final color = Color.lerp(Colors.white, Colors.white.withOpacity(0.8), t);
                      return SizeFadeTransition(
                        sizeFraction: 0.7,
                        curve: Curves.easeInOut,
                        animation: itemAnimation,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(35, 5, 35, 5),
                            child: Dismissible(
                              key: UniqueKey(),
                              child: Card(
                                elevation: elevation,
                                color: color,
                                child: Data[index].done ? Stack(
                                    children: <Widget>[
                                      ListTile(
                                        title: RichText(text: TextSpan(
                                            text: Data[index].Title,
                                            style: TextStyle(color: Colors.black,
                                                decoration: TextDecoration.lineThrough)),),
                                        subtitle: RichText(text: TextSpan(
                                            text: Data[index].Context,
                                            style: TextStyle(color: Colors.grey[800],
                                                decoration: TextDecoration.lineThrough)),),
                                      ),
                                      Center(
                                        child: SizedBox(height: 80, width: 80, child: Image(image: AssetImage('assets/checkItEmpty.png'),)
                                        ),
                                      )
                                    ]
                                ) :
                                ListTile(
                                  title: RichText(text: TextSpan(text: Data[index].Title,
                                      style: TextStyle(color: Colors.black)),),
                                  subtitle: RichText(text: TextSpan(text: Data[index].Context,
                                      style: TextStyle(color: Colors.grey[800])),),
                                  trailing:Handle (
                                    delay: const Duration(milliseconds: 100),
                                    child: Icon(
                                      Icons.list,
                                      color: Colors.grey,
                                    ),
                                  )
                                ),
                              ),

                              onDismissed: (direction) {
                                setState(() {
                                  restory.add(ToDoData(Title: Data[index].Title, Context: Data[index].Context, Index: index, done: Data[index].done));
                                  Data[index].done ? null : yetdone--;
//                                  listKey.currentState.removeItem(
//                                    index,
//                                        (BuildContext context, Animation<double> animation) => buildItems(scaffold,animation,index),
//                                    duration: Duration.zero,);
                                });
                                  setState(
                                        () => Data.removeAt(index),
                                  );



                                if (direction == DismissDirection.startToEnd) {
                                  Data.insert(yetdone, ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: true));
restory.last.Context, done: true));

                                  restory.removeLast();
                                  setState(() {});
                                }
                                else {
                                Scaffold.of(context).showSnackBar(
                                      SnackBar(content: Text(
                                          "${restory.last.Title} task has removed"),
                                        action: SnackBarAction(
                                            label: "UNDO",
                                            onPressed: () {
                                              Data.insert(restory.last.Index < yetdone ? restory.last.Index : yetdone, ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: false));
//                                            Data.add( ToDoData(Title: restory.last.Title, Context: restory.last.Context, done: false));
//                                              listKey.currentState.insertItem(restory.last.Index < yetdone ? restory.last.Index : yetdone);
                                              restory.removeLast();
                                              setState(() {
                                                yetdone++;
                                              });
                                            }
                                        ),
                                      ));
                                }
                              },
                              background: DoneBack(),
                              secondaryBackground: DeleteBack(),
                            )
                        )
                      );
                    },
                  );
                },

              ),

//              AnimatedList(
//                key: listKey,
//                initialItemCount:Data.length,
//                itemBuilder: (context,index,animation){
//                  return buildItems(Scaffold.of(context),animation,index);
//                },
//              ),
              Container(
                child: Align(
                  alignment: Alignment(0, 0.90),
                  child: RaisedButton(
                    padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
                    color: Colors.white,
                    onPressed: () => createAddFunction(context),
                    child: Text('Add Task',
                        style: TextStyle(fontSize: 20, color: Colors.black)),
                  ),
                ),
              ),
              ////////////////////////slide bar////////////////
              SlideBarMain(
                IsHome: false,
                key: _key,
              ),
            ]
        )
    );
  }
导入“dart:ui”;
进口“包装:颤振/cupertino.dart”;
进口“包装:颤振/材料.省道”;
导入“包:flatterapp/SlideBar/Function/SlideBarMain.dart”;
导入“包:flatterapp/SlideBar/Function/ToDoClass.dart”;
导入“package:implicitly_animated_reorderable_list/implicitly_animated_reorderable_list.dart”;
导入“package:implicitly_animated_reorderable_list/transitions.dart”;
类ToDo扩展StatefulWidget{
@凌驾
_ToDoState createState()=>\u ToDoState();
}
类_tostate扩展状态{
最终全局键=全局键();
最终GlobalKey formKey=GlobalKey();
最终GlobalKey listKey=GlobalKey();
List restory=[ToDoData(Title:null,Context:null,done:false)];
列表数据=[
ToDoData(标题:“完成ToDo”,上下文:“快速完成”,完成:false),
];
int-yetdone=1;
字符串标题;
字符串TodoContext;
//bool inReorder=错误;
//
//滚动控制器滚动控制器;
//
//@覆盖
//void initState(){
//super.initState();
//scrollController=scrollController();
//  }
void onReorderFinished(列出新项){
//scrollController.jumpTo(scrollController.offset);
设置状态(){
//inReorder=false;
资料
…清除()
..添加所有(新项目);
});
}
Widget buildTitle(){
//创建标题限制
返回TextFormField(
装饰:输入装饰(标签文本:“标题”),
最大长度:50,//75
//忽略:缺少返回
验证器:(字符串值){
if(value.isEmpty){
返回“需要标题”;
}
},
onSaved:(字符串值){
标题=价值;
},
);
}
小部件buildTodoContext(){
//创建上下文
返回TextFormField(
装饰:输入装饰(标签文本:“上下文”),
最大长度:100,
onSaved:(字符串值){
TodoContext=值;
},
);
}
createAddFunction(构建上下文){
//新任务创建者屏幕
返回showDialog(上下文:上下文,生成器:(上下文){
返回警报对话框(
标题:文本(“添加新ToDo”),
内容:容器(
保证金:全部(24),
子项:窗体(键:formKey,子项:Column)(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
buildTitle(),
buildTodoContext(),
尺寸箱(高度:50,),
升起的按钮(
子项:文本(“保存”),
已按下:(){
formKey.currentState.save();
如果(!formKey.currentState.validate()){
返回;
}
否则{
插入(yetdone,ToDoData(标题:标题,上下文:TodoContext,完成:false,);
设置状态(){
yetdone++;
});
Navigator.of(context.pop();
};
},
)
],
)
))
);
});
}
小部件回写(){
//将任务向右滑动时的背景
返回容器(
对齐:alignment.centerLeft,
填充:仅限边缘设置(左:20.0),
颜色:颜色。绿色,
子:常量图标(Icons.done,颜色:Colors.white,),
);
}
小部件DeleteBack(){
返回容器(
对齐:alignment.centerRight,
填充:仅限边缘设置(右侧:20.0),
颜色:颜色,红色,
子:常量图标(Icons.delete,颜色:Colors.white,),
);
}
@凌驾
小部件构建(构建上下文){
返回脚手架(//屏幕背景
背景颜色:颜色。灰色[600],
appBar:appBar(
背景颜色:颜色。灰色[900],
行动:[
图标按钮(
图标:图标(Icons.add),
onPressed:()=>createAddFunction(上下文),
),
],
领先:
图标按钮(
图标:图标(图标.设置),
按下:()=>_键.currentState.SwitchFunc(),
),
标题:文本(“待办事项”),
标题:对,
),
正文:
堆栈(//任务列表)
儿童:[
隐式iMatedReorderableList(
项目:数据,
收缩膜:对,
艾瑞特塞萨酒店