I want to validate "Text" in flutter not (TextFormField or Textfield), I want to check if the text is empty and if the text is empty then I want it to navigate to new page automatically.
So basically there's a Text widget where I am displaying data from Api using get method so what I want is, if the text widgets are empty, I want it to navigate to login page.
CodePudding user response:
You need to store the string content of the concerned Text widget in a variable. Then you need to call a conditional operation on it to move to the new page.
Example:
String check = ""; (check == "") ? Navigator.pushNamed((context), "/desired-routeName") : Text(check),
CodePudding user response:
simply you can check by == "";
for example:
String myText = ""
bool isEmpty(String text) => text == "";
isEmpty(myText); //returns true
//now set some value
myText = "some value"
isEmpty(myText); //returns false
then you can navigate based on condition like:
if (isEmpty(myText))
{ //navigation logic goes here
} else {
}
CodePudding user response:
Method 1. You can declare a variable and pass it to the Text widget. Put your condition on that variable.
Method 2.
Save your Text Widget into a variable and use the data: String?
property to access the text inside Text widget.
final textWidget = const Text("Hello World");
if(textWidget.data?.isEmpty()) {
//...
}
else {
//...
}
You can put the condition in didChangeDipendencies()
or initState()
if you wanna to navigate to new page without any click event.