I made following simple class to allow entering a string:
import 'package:flutter/material.dart';
class MyDialog {
late TextEditingController _controller;
Future<String> showMyDialog(BuildContext context) async {
_controller = TextEditingController();
final result = await showDialog(
context: context,
builder: (BuildContext context) => _buildMyDialog(context),
);
_controller.dispose();
return result;
}
Widget _buildMyDialog(BuildContext context) {
return AlertDialog(
title: const Text('Enter string: '),
content: TextField(
autofocus: true,
controller: _controller,
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(_controller.text);
},
child: const Text('OK'),
),
],
);
}
}
and I call it like this:
final dialog = MyDialog();
final result = await dialog.showMyDialog(context);
Unfortunately I get following error:
A TextEditingController was used after being disposed.
Why does it happen and how to fix it? I don't use the controller anywhere after disposing it after all.
CodePudding user response:
On showMyDialog it is getting new TextEditingController every time, we can comment _controller.dispose();. Also, it is possible to get null on this method, therefore it will be better using
Future<String?> showMyDialog(...){...}
Another thing we can do making it nullable
class MyDialog {
TextEditingController? _controller;
Future<String?> showMyDialog(BuildContext context) async {
_controller = TextEditingController();
final String? result = await showDialog(
context: context,
builder: (BuildContext context) => _buildMyDialog(context),
);
_controller = null;
return result;
}
//....
You can check about _dependents.isEmpty': is not true
