Как исправить RangeError после удаления данных из Firebase и удаления их из списка флаттера? - PullRequest
0 голосов
/ 25 января 2020

Я получаю RangeError, когда удаляю данные из базы данных Firebase в реальном времени с помощью приложения флаттера.

Вот ошибка

I / flutter (10577): было сгенерировано следующее RangeError: I / flutter (10577): RangeError (index): Неверное значение: Допустимое значение диапазон пуст: 0

И ошибка появляется после выполнения этой функции

_deleteTask (int index)

Ниже приведен код

import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import '../Task.dart';
import 'package:intl/intl.dart';
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FirebaseDatabase database = new FirebaseDatabase();
  DatabaseReference databaseReference;
  List<Task> tasks = List();
  Task task;

  @override
  void initState() {
    super.initState();
    databaseReference = database.reference().child("Notes");
    task = Task("", "");
    databaseReference.onChildAdded.listen(_childAdded);
    databaseReference.onChildChanged.listen(_childChanged);
    //databaseReference.onChildRemoved.listen(_childDlt);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black54,
        title: Text(
          "Todo",
          style: TextStyle(color: Colors.white),
        ),
        actions: <Widget>[
          IconButton(
            icon:Icon(Icons.done_all),
            onPressed: (){
              setState(() {
                databaseReference.remove();
              });
            },
          )

        ],
      ),
      body: Container(
        color: Colors.black,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
              Flexible(
                child: FirebaseAnimatedList(
                    query: databaseReference,
                    itemBuilder: (context, DataSnapshot snapshot,
                        Animation<double> animation, int indexxx) {
                      return Card(
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                        color: Colors.white30,
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ListTile(
                            onTap: ()=>_editTask(indexxx),
                            title: Text("${tasks[indexxx].task}",style: TextStyle(color: Colors.white,fontSize: 18,fontWeight: FontWeight.w600),),
                            subtitle: Text("Created on: ${tasks[indexxx].date}",style: TextStyle(color: Colors.white,fontStyle: FontStyle.italic)),
                            trailing: IconButton(
                              icon: Icon(Icons.remove_circle,color: Colors.red,),
                              onPressed: ()=>_deleteTask(indexxx),
                            )
                          ),
                        ),
                      );
                    }),
              )
            ],
          ),
        ),
      ),
      floatingActionButtonLocation:FloatingActionButtonLocation.centerDocked,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add,color: Colors.blue,size: 40,),
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.0)
        ),
        onPressed: ()=>_newTask(),
        //label: Text("New Task"),
      ),
    );
  }
  _newTask(){
    TextEditingController textEditingController=TextEditingController();
    var alert=AlertDialog(
      title: Text("Add New Task"),
      content: TextField(
        controller: textEditingController,
        decoration: InputDecoration(
          labelText: "Enter Text"
          //hintText: "Enter Text",
        ),
        autofocus: true,
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("Cancel"),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        FlatButton(
          child: Text("Add"),
          onPressed: (){
            String text=textEditingController.text;
            DateTime now = DateTime.now();
            String formattedDate = DateFormat('MMM d,y').format(now);
            task.date=formattedDate;
            task.task=text;
            databaseReference.push().set(task.toJson());
            Navigator.of(context).pop();
          },
        ),
      ],
    );
    showDialog(context: context,builder:(context){
      return alert;
    });
  }

  _editTask(int index) {
    TextEditingController textEditingController=TextEditingController();
    textEditingController.text=tasks.elementAt(index).task;
    var alert=AlertDialog(
      title: Text("Edit Task"),
      content: TextField(
        controller: textEditingController,
        decoration: InputDecoration(
            labelText: "Enter Text",
          //hintText: "Enter Text",
        ),
        autofocus: true,
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("Cancel"),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        FlatButton(
          child: Text("Update"),
          onPressed: (){
            String text=textEditingController.text;
            DateTime now = DateTime.now();
            String formattedDate = DateFormat('MMM d,y').format(now);
            task.date=formattedDate;
            task.task=text;
            databaseReference.child(tasks.elementAt(index).key).update(task.toJson());
            setState(() {
              Navigator.of(context).pop();
            });
          },
        ),
      ],
    );
    showDialog(context: context,builder:(context){
      return alert;
    });
  }

  _deleteTask(int index) {
      setState(() {
        databaseReference.child(tasks.elementAt(index).key).remove();
        tasks.removeAt(index);
      });
  }

  void _childAdded(Event event) {
    setState(() {
      tasks.add(Task.fromSnapshot(event.snapshot));
    });
  }

  void _childChanged(Event event) {
    var oldTask=tasks.singleWhere((entry){
      return event.snapshot.key==entry.key;
    });
    setState(() {
      tasks[tasks.indexOf(oldTask)]=Task.fromSnapshot(event.snapshot);
    });
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...