The Problem
The isEmpty
check is returning true
for a non-empty String field. My guess is – TextEditingController’s String metadata is not updating with string update from an async load.
- I’m not sure if I’m missing something obvious or if this is a Dart/Flutter bug.
- Is there an idiomatic way to accomplish this check?
Here’s my code
var textController = TextEditingController();
@override
void initState() {
super.initState();
init();
}
void init() async {
final foo = await FooProvider.instance.getFoo(widget.uuid);
textController.text = foo.title;
}
The actual usage of the textController,
GestureDetector(
onTap: textController.text.isEmpty
? () {
debugPrint('Empty - ${textController.text}');
}
: () {
// rest of the code
2
Answers
If you change the text of
TextEditingController
, your widget wouldn’t be rebuilt automatically.Because
setState
never has been called.Solution
textController
withValueListenableBuilder
if you want to listen value changing.setState
manually iftextController
value changed.This will rebuild entire widget tree of your widget.
isEmpty
inGestureDetector.onTap
by @Ivo ‘s comment you can check
isEmpty
inonTap
. This works becauseisEmpty
is evaluated at timeonTap
called.An alternative solution is to do the check inside a single implementation of
onTap
instead of two different ones, like this