It’s probably easy to understand if you look at it from the bottom.
final TextEditingController _textEditingController = TextEditingController();
PreferredSizeWidget _appBar() {
final deviceSize = MediaQuery.of(context).size;
return AppBar(
flexibleSpace: SafeArea(
child: Row(
children: [
Container(
width: deviceSize.width / 10 * 8,
decoration: BoxDecoration(
color: const Color(0xFFf4f4f4),
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
const Expanded(
child: TextField(
decoration: InputDecoration(
// filled: true,
// fillColor: Colors.blue,
border: InputBorder.none,
hintText: 'hintText',
hintStyle: TextStyle(
color: Color(0xFF888888),
fontSize: 14,
fontWeight: FontWeight.w500,
),
contentPadding: EdgeInsets.only(left: 16, bottom: 6),
),
),
),
if (_textEditingController.text.isNotEmpty)
InkWell(
onTap: () {
setState(() {
_textEditingController.clear();
});
},
child: Image.asset('assets/images/delete.png'),
),
.
.
.
.
.
],
),
],
),
This code is when the text is in the text field, ElevatedButton is created.
But even if there is text in the text field, it doesn’t happen.
What can I do to appear the button?
2
Answers
The
_textEditingController.text.isNotEmpty
part is only "read" when the_appBar()
method is called, so probably in your widget’sbuild
method. This app bar doesn’t know it should rebuild when the text controller value changes. You have a few options to choose from on how to solve it, two of them, among others are as follows:Wrap your
InkWell
with theif
inListenableBuilder
. TheTextEditingController
is aChangeNotifier
, which is aListenable
. Something that you can listen to. It "fires" when the controller’s value changes.If the text is empty I’m returning a
const SizedBox()
, which is basically a widget with no size and contents, because I need to return something in thebuilder
.In the
initState()
of yourStatefulWidget
addListener
on the_textEditingController
and in its callback, callsetState()
whenever the value of the controller changes. This will rebuild this stateful widget on every controller change, so the condition in theif
will be read again and the button will appear when necessary.Also, looking at your code example, I see one issue and one thing you may not be aware of.
setState
is only necessary when you want your widget to be rebuilt. Text editing controller methods don’t need to be called inside asetState
, because you pass this controller to a text field that listens on its changes. You’d need thissetState
only if you wanted to rebuild your stateful widget.First, declare a variable after _textEditingController :
bool isTextFieldEmpty = false;
Then Do This in TextField:
}
Then Do this Where you want to put your Buttton :