Flutter let us display error message based on the wrong input. This is possible with InputDecoration. Using the widget we can pass Error message as follows.
TextField( style: inStyle, decoration: InputDecoration( errorText: 'Date can\'t be empty', labelText: 'Expected Completion Date', border: OutlineInputBorder(), ), ),
How to display Error programmatically
In StatefullWidget we can use setState method to update the UI. We can do update UI based on the error we found by doing the following
- Create variable in your State class, say bool dateError
- Use the variable in the errorText of the InputDecoration
- Update the variable in a event like Onpressed or OnTap of a widget.
The Error variable
The Error variable can be declared in the State portion of the widget as follows
class _HomePageState extends State<HomePage> { //Error variables bool dateError = false; ......
Checking the Error on errorText
We can check on the variable for showing errorText message using the conditional operator and the dateError variable .
TextField( decoration: InputDecoration( errorText: dateError ? 'Date can\'t be empty', : null labelText: 'Expected Completion Date', border: OutlineInputBorder(), ), ),
Every time we a change the errorDate variable to true the message will appear. How do we change it? The Flutter Statefull widget can only detect change in a variable by using state, so it can update the UI.
Updating the dateError
Using an event listener and setState () we can update the dateError. The UI only detect change while it is done with setState ().
onPressed: () { try { setState(() { txtDate.text.isEmpty ? dateError = true : dateError = false; ) } }
Here txtDate is a TextFieldEditingcontroller used to capture the input value from TextField.
As you can see the UI only show errorText while the dateError set to true .
The following list of posts may help you.
- How to load content into div using jQuery
- How to add web/desktop support for existing flutter app in OpenSUSE
- How to add web/desktop support for existing flutter app in Ubuntu
- How to enable Flutter Web support in Ubuntu Linux
- How to enable Flutter Desktop support in Ubuntu Linux
- How to install Flutter on Ubuntu Linux
- How to fix flutter windows app exception plugins requires symlink support ?
- How to add web/desktop support for existing flutter app
- How to enable Flutter Web support in openSUSE Linux
- Enable Flutter Web support on Windows
One thought on “Flutter : Showing errorText programmatically in a StatefullWidget”