[英]I want to validate "Text" in flutter not (TextFormField or Textfield)
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.我想验证 flutter 中的“文本”不是(TextFormField 或 Textfield),我想检查文本是否为空,如果文本为空,那么我希望它自动导航到新页面。
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.所以基本上有一个文本小部件,我使用 get 方法显示来自 Api 的数据,所以我想要的是,如果文本小部件为空,我希望它导航到登录页面。
You need to store the string content of the concerned Text widget in a variable.您需要将相关 Text 小部件的字符串内容存储在变量中。 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),
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 {
}
Method 1. You can declare a variable and pass it to the Text widget.方法 1. 您可以声明一个变量并将其传递给 Text 小部件。 Put your condition on that variable.
把你的条件放在那个变量上。
Method 2. Save your Text Widget into a variable and use the data: String?
方法 2. 将您的文本小部件保存到变量中并使用
data: String?
property to access the text inside Text widget.属性来访问 Text 小部件中的文本。
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.如果您想在没有任何点击事件的情况下导航到新页面,您可以将条件放入
didChangeDipendencies()
或initState()
中。
If you get data from api, i would recommend you to validate your string data with regular expressions.如果您从 api 获取数据,我建议您使用正则表达式验证您的字符串数据。 To check empty strings you can se the follow regex.
要检查空字符串,您可以使用以下正则表达式。
RegExp regExp = new RegExp(r"^$",caseSensitive: false, multiLine: false,);
if(regExp.allMatches(yourValue)){
Navigator.push(context,MaterialPageRoute(builder: (context) => const SecondRoute()),);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.