flutter

where to dispose of TextEditingController in a stateless widget?


I am using provider for flutter state management, and I have this code that allows editing a property by using a dialog with a text field.

TextButton(
  onPressed: () async {
    final _textController = TextEditingController();
    final result = await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('....'),
          content: TextField(
            controller: _textController,
            actions: [
              TextButton(
                child: const Text('Cancel'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
              ),
              TextButton(
                child: const Text('Add'),
                onPressed: () {
                  Navigator.pop(context, _textController.text);
                },
              ),
            ],
        );
      },
    );
    if (result != null) {
      context.read<PatientProvider>().updatePatientName(result as String);
    }
  },
  child: Text(
    context.watch<PatientProvider>().patient.name
  ),
)

Where do I dispose of _textController?


Solution

  • Dispose the _textController after alert dialoge. After await showDialog, the dialog is closed, and we dispose of the controller right away.

    _textController.dispose();
    

    Full solution:

    
    TextButton(
      onPressed: () async {
        final _textController = TextEditingController();
        final result = await showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: const Text('....'),
              content: TextField(
                controller: _textController,
                actions: [
                  TextButton(
                    child: const Text('Cancel'),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                  ),
                  TextButton(
                    child: const Text('Add'),
                    onPressed: () {
                      Navigator.pop(context, _textController.text);
                    },
                  ),
                ],
            );
          },
        );
     
        // Dispose the controller after alert dialog is closed.
        _textController.dispose();
    
        if (result != null) {
          context.read<PatientProvider>().updatePatientName(result as String);
        }
      },
      child: Text(
        context.watch<PatientProvider>().patient.name
      ),
    )