Search code examples
firebasefluttergoogle-cloud-firestoreflutter-providerflutter-showmodalbottomsheet

Flutter: edit new object from object incorrectly changing old object


I am trying to include an edit object feature in my productivity tracking app. I am using Flutter, Firestore, and Provider. I am trying to allow the user to update a task (for ex.) with different properties in a modal bottom sheet. The update aspect is working. If a user presses the update button it correctly updates Firestore and displays the information correctly. My issue is that when I cancel out of the modal, signaling a cancellation of the update, it is still updating the original task object. I even tried having a cancel button that would dispose of the provider and the result was the same. I am not sure why this is happening. If I reload the app, the correct values, that are stored in Firestore, are displayed. Here is a video of what is happening:

enter image description here

This is my Task model:

class Task {
  String taskID;
  String taskName;
  Project project;
  Status status;
  DateTime dueDate;
  DateTime createDate;

  Task({taskID, taskName, project, status, dueDate, createDate})
      : taskID = taskID as String ?? '',
        taskName = taskName as String ?? '',
        project = project as Project ?? Project(),
        status = status as Status ?? Status(),
        dueDate = dueDate as DateTime ?? DateTime(0001, 01, 01, 0, 0, 0, 0, 555),
        createDate = createDate as DateTime ?? DateTime.now();

This is my Provider State:

class TaskEditState extends ChangeNotifier {
  Task newTask;

  TaskEditState({newTask}) : newTask = newTask as Task ?? Task();

  void updateTaskName(String taskName) {
    newTask.taskName = taskName;
    notifyListeners();
  }

  void updateTaskProject(Project project) {
    newTask.project = project;
    notifyListeners();
  }

  void updateTaskStatus(Status status) {
    newTask.status = status;
    notifyListeners();
  }

  void updateTaskDueDate(DateTime dueDate) {
    if (newTask.dueDate.microsecond == 555) {
      newTask.dueDate = dueDate;
    } else {
      final DateTime temp = newTask.dueDate;
      newTask.dueDate = DateTime(
          dueDate.year, dueDate.month, dueDate.day, temp.hour, temp.minute);
    }
    notifyListeners();
  }

  void updateTaskDueTime(TimeOfDay dueTime) {
    if (newTask.dueDate.year == 0) {
      newTask.dueDate = DateTime(0, 0, 0, dueTime.hour, dueTime.minute);
    } else {
      final DateTime temp = newTask.dueDate;
      newTask.dueDate = DateTime(
          temp.year, temp.month, temp.day, dueTime.hour, dueTime.minute);
    }
    notifyListeners();
  }

  void addTaskCreateDate(DateTime createDate) {
    newTask.createDate = createDate;
  }

This is my Edit Bottom Sheet

  TaskEditBottomSheet({
    Key key,
    this.isUpdate,
    this.task,
  }) : super(key: key);

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => TaskEditState(newTask: task),
      builder: (context, child) {
        final TaskEditState taskEditState = Provider.of<TaskEditState>(context);
        final TaskService taskService = Provider.of<TaskService>(context);
        print(taskEditState.newTask.project.projectName);
        return Container(
            margin: EdgeInsets.all(20),
            child: Column(mainAxisSize: MainAxisSize.min, children: [
              TextFormField(
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please Enter Project Name';
                  }
                  return null;
                },
                decoration: InputDecoration(
                    hintText: taskEditState.newTask.taskName.isEmpty
                        ? 'Enter Task Name'
                        : taskEditState.newTask.taskName),
                textAlign: TextAlign.center,
                onChanged: (newText) {
                  taskEditState.updateTaskName(newText);
                },
              ),
              ProjectPicker(
                saveProject: taskEditState.updateTaskProject,
                child: ListTile(
                  leading: Icon(
                    Icons.circle,
                    color: Color(taskEditState.newTask.project.projectColor),
                  ),
                  title: Text(
                      taskEditState.newTask.project.projectName.isEmpty
                          ? 'Add Project'
                          : taskEditState.newTask.project.projectName,
                      style: Theme.of(context).textTheme.subtitle1),
                  trailing: Icon(Icons.arrow_drop_down_rounded,
                      color: Theme.of(context).unselectedWidgetColor),
                ),
              ),
              StatusPicker(saveStatus: taskEditState.updateTaskStatus),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text('Due: ', style: Theme.of(context).textTheme.subtitle1),
                  OutlinedButton.icon(
                    onPressed: () => DateAndTimePickers().selectDate(
                        context: context,
                        initialDate: taskEditState.newTask.dueDate.year == 1
                            ? DateTime.now()
                            : taskEditState.newTask.dueDate,
                        saveDate: taskEditState.updateTaskDueDate),
                    icon: Icon(Icons.today_rounded),
                    label: Text(taskEditState.newTask.dueDate.year == 1
                        ? 'Add Due Date'
                        : DateTimeFunctions().dateTimeToTextDate(
                            date: taskEditState.newTask.dueDate)),
                  ),
                  OutlinedButton.icon(
                    onPressed: () => DateAndTimePickers().selectTime(
                        context: context,
                        initialTime:
                            taskEditState.newTask.dueDate.microsecond == 555
                                ? TimeOfDay.now()
                                : TimeOfDay.fromDateTime(
                                    taskEditState.newTask.dueDate),
                        saveTime: taskEditState.updateTaskDueTime),
                    icon: Icon(Icons.alarm_rounded),
                    label: Text(taskEditState.newTask.dueDate.microsecond != 555
                        ? DateTimeFunctions().dateTimeToTextTime(
                            date: taskEditState.newTask.dueDate,
                            context: context)
                        : 'Add Due Time'),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.symmetric(vertical: 20),
                child:
                    ElevatedButton.icon(
                  icon: Icon(Icons.check_circle_outline_rounded),
                  label: Text(isUpdate ? 'Update' : 'Add'),
                  onPressed: () {
                    if (_formKey.currentState.validate()) {
                      isUpdate
                          ? taskService.updateTask(
                              taskID: task.taskID,
                              updateData: taskEditState.newTask.toFirestore())
                          : taskService.addTask(
                              addData: taskEditState.newTask.toFirestore());
                      Navigator.pop(context);
                    }
                  },
                ),
              )
            ]));
      },
    );
  }
}

And finally, this is the function that calls the bottom sheet:

class EditBottomSheet {
  Future<dynamic> buildEditBottomSheet(
      {BuildContext context, Widget bottomSheet}) {
    return showModalBottomSheet(
        context: context,
        enableDrag: true,
        // isDismissible: false,
        isScrollControlled:
            true, // Allows the modal to me dynamic and keeps the menu above the keyboard
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(25), topRight: Radius.circular(25))),
        builder: (BuildContext context) {
          return bottomSheet;
        });
  }
}

Any help will be greatly appreciated, thanks!


Solution

  • I found out my issue. I am not sure if this is a language difference or not between Dart and other things I've used. In the Provider State field, I am setting the new Task equal to the old Task:

    TaskEditState({newTask}) : newTask = newTask as Task ?? Task();
    

    I learned that this is setting the new Task equal to the old Task's reference. So when I changed anything regarding the new Task it also updated the old Task as well. I am guessing this is because they are actually the same object versus the new Task being a copy of the old Task. So I created a model function for all my models that copy the original task and return the copy. This has completely fixed my issue. Here is the updated Provider State File:

    TaskEditState({this.oldTask}) {
        if (oldTask != null) {
          newTask = oldTask.copyTask();
        } else {
          newTask = Task();
        }
      }
    

    Here is my copy function:

    Task copyTask() {
        return Task(
            id: id ?? '',
            taskName: taskName ?? '',
            project: project ?? Project(),
            status: status ?? Status(),
            dueDate: dueDate ?? DateTime(0001, 01, 01, 0, 0, 0, 0, 555),
            createDate: createDate ?? DateTime.now());
      }