Search code examples
flutterstatelesswidgetflutter-showmodalbottomsheettexteditingcontroller

Flutter Bottomsheet reload problem after dismissing keyboard


In a todoapp , am trying to edit a single task from a list of Tasks. After clicking on edit icon , I was able to open a bottomsheet widget using showmodalbottomsheet function with pre filled two text fields using texteditingcontrollers. When I tried to edit a single text field and dismissed the keyboard, the bottomsheet is loading again the previous value.I am unable to save my edited value..pls help

I used stateless bottomsheet widget.

Heres the Code. I know this not ideal way of coding. but am trying to get to work the functionality, later i will work on optimisation.

Tasklist.dart

IconButton( icon: Icon(Icons.edit), onPressed: (){ _startEditTask(context, index);//index is the single task from the lisview },),

void _startEditTask(BuildContext ctx, int index){
    showModalBottomSheet(context: ctx, builder: (btx){
      return GestureDetector(
        onTap: (){},
        child: EditTask(_taskList[index].taskName,_taskList[index].description,index,_editTask),
      );
    });
  }

void _editTask(String taskName, String description, int index){
    setState(() {
      _taskList[index].taskName = taskName;
      _taskList[index].description = description;
    });
  }

EditTask.dart

class EditTask extends StatelessWidget {
  EditTask(this.taskName,this.description,this.index,this.editTask);
  String taskName;
  String description;
  int index;
  final Function editTask;
  var taskNameController = TextEditingController();
  var taskDescriptionController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    taskNameController.text = taskName;
    taskDescriptionController.text = description;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        TextField(
          controller: taskNameController,
          decoration: InputDecoration(
              labelText: 'Task Name'
          ),

        ),
        TextField(
          controller: taskDescriptionController,
          decoration: InputDecoration(
              labelText: 'Description'
          ),
        ),
        TextButton(
          child: Text('Save Task'),
          onPressed: (){
            editTask(taskNameController.text,taskDescriptionController.text,index);
          Navigator.of(context).pop();
          },
        )
      ],
    );
  }
}

Solution

  • StatelessWidget
    

    to

    StatefulWidget 
    

    will solve your issue ---- try now


    class EditTask extends StatelessWidget
    

    to

    class EditTask extends StatefulWidget