I want to validate "Text" in flutter not (TextFormField or Textfield) - flutter

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.

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),

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. 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.

If you get data from api, i would recommend you to validate your string data with regular expressions. 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()),);
}

Related

value of my List is changing when i delete text from TextField Flutter

i have a list that i want to search in (I remove the values that don't match my search), I write the search word in a TextField and save the initial list in order to show it again when the user deletes the search word (or want to search for another thing) .
i can save the list in a variable but the issue is when I start deleting the search word the value of my initial list becomes the same that the list I show for the search !
onChanged: (val) {
//i save the list before doing any change here
if (_initList == null) _initList = myList;
// this part works fine
if (val.length > 2)
setState(() {
myList.removeWhere((element) => !element
.getName()
.toLowerCase()
.contains(val.toLowerCase()));
});
// when i’m in the else, when i try to print _initList value i find that it’s the same as myList
// the value of _initList is not changing anywhere else in the code
else {
setState(() {
myList = _initList;
});
}
},
when you do this
if (_initList == null) _initList = myList;
both variables will point to the same list. changes to one list will also change the other, because they are in fact the same list. What you want to do is safe a copy of the list in it. You can do it by calling toList() on it, like
if (_initList == null) _initList = myList.toList();

How to prevent html tag in a flutter text widget

I have a Flutter text widget in my login screen that users enters their username in plain text.
How can I prevent then from entering HTML characters in the field.
For example, they enter <p>myname</p>
Thanks
You can try using RegEx for that like so
String stripHtml(String s) {
if (s.isEmpty) {
return s;
}
var regex = RegExp(r'<[^>]*>');
return s.replaceAll(regex, '');
}

How to put variable text and custom text together in flutter

If there is an inherited variable called id, I would like to display widget.index and ": problem number" together on one line on the screen.
ex)
problem(text) 1(list variable)
problem(text) 2(list variable)
Is there a way to get a variable in a list like the one above and display it on the screen along with text?
You can use $ in a string
String someString = 'problem id: ${problem(text)} and widget index :${widget.index}';

How to replace text with image(is it possible in flutter)

var replaced = text.replaceAll(regExp, '*');
Instead of the asterisk mark can we replace this with actual image..
Ok. So you have bunch of emojis stored locally. and you have to replace a text with emoji.
I don't have a perfect answer. but how you can achieve a path that i can show.
Using a map. as you are suppose to change the text for an image there must be a pair. so you can define a map for it. a key will be a text and the value will be the path of the emoji. considering your folder as a images and format is png.
Map<String, String> myData = {"like" : "images/like.png", "time":
"images/time.png"};
and so on. Like this you can create a full map of it. if it's limited like 30 -40 records that you will do manually.
Now you can perform operations on that. Suppose you have String value = " I like your shirt!";
so we need to scan the string and then search every word inside tha map and replace if you found it.
the code looks like this
void main() {
//your value that you are going to scan
String str = " I like your shirt";
//Defining the map
Map<String, String> data = {"like" : "images/like.png", "shirt" :
"images/shirt.png", "happy" : "images/happy.png"};
//function that will do the changes and display
void replaceTextWithEmojis(String value, Map<String, String> data){
//splitting the value into the array or list of items so we can iterate easily
List<String> inputvalues = str.split(" ");
//looping through the text
for (int i =0; i<inputvalues.length; i++){
//checking where that text is present in the emojis map or not.
if(data.containsKey(inputvalues[i])){
//this will replace the text with the path for that key
inputvalues[i] = data[inputvalues[i]];
}
} //end of the for loop
print(inputvalues);
}
replaceTextWithEmojis(str, data);
}
This will replace with the desired values. But You want to display a image between the text. That's what something difficult. I don't think you can do it in flutter. Or it will be like you need to identify the position of the replaceable text and then break the string and store it in other variable. append the image at the breakpoint. so at the place where we are replacing with the map you can add a widget(child ImageProvider(inputvalue[i]));
I would suggest you to use unicode for emojis.
you can use the package for unicode emjois : https://pub.dev/packages/emojis
Also they will give you better performance.
/// Replace an emoticon or any string token with an image having a tooltip and Help cursor.
static List<Widget> replaceEmoji(final String text, final String fromToken, final String toImgTooltip, final String toImg) {
Widget _getImage(final String path, final String tooltip) => MouseRegion(
cursor: SystemMouseCursors.help,
child: Tooltip(message: tooltip, child: Image.asset(path)),
);
if (!text.contains(fromToken)) {
return [Text(text)];
}
final result = <Widget>[];
var buffer = text;
var n = -1;
while (true) {
n = buffer.indexOf(fromToken);
if (n != 0) {
result.add(Text(buffer.substring(0, n)));
}
result.add(_getImage(toImg, toImgTooltip));
buffer = buffer.substring(n + fromToken.length);
if (buffer.isEmpty) {
break;
}
}
return result;
}
You use it as follows:
...
Wrap(
children: replaceEmoji('my :) face - :):)', ':)', 'smile', 'assets/images/emoji/smile.png')
)
...

get widget by id in gwt

I have a bunch of TextBox-es generated dynamically. At the step of creation I'm assigning the ID property for them.
e.g.
id = ...
Button b = new Button();
b.setText("add textbox");
b.addClickHandler(new Clickhandler() {
Textbox tb = new TextBox();
tb.getElement().setId(Integer.toString(id));
tb.setText("some text");
}
id += 1;
I need to access them later by their IDs, but I cannot do it.
I tried to use the DOM object in order to get a widget, but it produces an exception:
String id = "some id";
Element el = DOM.getElementById(id);
String value = el.getAttribute("value"); - this line produces an exception.
I've also tried to use el.getInnerText, el.getNodeValue - no luck. I have see in the chrome debugger - the textboxes don't have the 'value' property.
you can get the widget associated to an element this way:
public static IsWidget getWidget(com.google.gwt.dom.client.Element element) {
EventListener listener = DOM
.getEventListener((com.google.gwt.dom.client.Element) element);
// No listener attached to the element, so no widget exist for this
// element
if (listener == null) {
return null;
}
if (listener instanceof Widget) {
// GWT uses the widget as event listener
return (Widget) listener;
}
return null;
}
Since you are constructing your textboxes in gwt java code, why not put them into a map and access them later?
One thing to keep in mind is the difference between an attribute and a property in HTML/DOM. In your example, "value" is a property. You could try Element#getPropertyString. It used to be that attributes and properties were used interchangeably, but in modern browsers that's no longer the case.