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.