Check variable run time Type in flutter with conditions like "123" is present as a String but is a int so how can i check this? - flutter

I have to check runtime Type of value for this I am using :-
for Example:-
String a = "abc";
int b = 123;
var c = "123"; //this is int value but because of this double quotes is represent as a String
a.runtimeType == String //true
b.runtimeType == int // true
c.runtimeType == String //true
c.runtimeType == int //false
a = "abc" // okay
b = 123 //okay
c = "123" //is issue
now I have to call a api with only String body in this case :-
this c is called the API because is String but i know this is a int value which is present as a String, so I have to stop this.
How can I check this??
when I am using try catch so my program is stopped because of FormatException error.
Note:- I don't know the real value of C, may be its "123" or "65dev" or "strjf" this value is changed every time.
and if i am parsing this in int to this return an error in many case.

Ok i understood that you want to pass "123" by checking and if it is int you are passing it , My question is what you will do if it is "123fe" you are going to pass as string? or you will pass nothing.

I don't know how you're passing it to API but if you wanna pass integer value from string quoted variable, you can parse/convert to integer like this.
int.parse(c);
either you can pass it directly or you can store in another variable and pass that variable.
Alternatively if you've int value and to have to pass it as a string, simply parse like this
integerValue.toString();
according to your code
b.toString();
Edit
String a = '20';
String b = 'a20';
try{
int check = int.parse(a);
//call your api inside try then inside if
if(check.runtimeType == int){
print('parsed $check');
}
}
catch(e){
print('not parsed ');
//handle your error
throw(e);
}

This will definitely help you!
String name = "5Syed8Ibrahim";
final RegExp nameRegExp = RegExp(r'^[a-zA-Z ][a-zA-Z ]*[a-zA-Z ]$');
print(nameRegExp.hasMatch(name));
//output false
name = "syed ibrahim";
print(nameRegExp.hasMatch(name));
//output true
Just check the output and based on that boolean value invoke api call
I hope it will done the work

Related

Is there any way in flutter for converting String to a new Function?

I have a text field and this text field gives me a String and I want to convert this String to a Function. for example >>>
"{
print("a")
}"
this is the String and I want this String to be a function like this>>>
{
print("a")
}
There is a way in my mind.
using textField with text controller to get data after user type
to use that string to make sure that string which user typed will meet two different regex patterns which shown on the pictures.
and then using if..else to invoke print().
RegExp regExp1 = new RegExp("your algorium"); <- to find print
RegExp regExp2 = new RegExp("your algorium"); <- to find "xxxx"
var a = regExp1.hasMatch("{print("a")}")
var b = regExp2.hasMatch("{print("a")}")
if ( a && b)
{
String test = regExp2.stringMatch("{print("a")}").toString()
print(test);
}

Conditional Operators (??) issues in dart

void main() {
print("Conditional Operators:");
// small if else
var a1 = 100;
var b2 = 20;
var istrue = (a1 < b2) ? 'True' : 'False';
print(istrue);
// check if null or print name
var name1;
var check = name1 ?? "This is Null";
print(check);
var name = "Abdulelah";
var checknot = name ?? "This is Null";
print(name);
}
I don't how i fix this problem in line 16
yellow error said:
The left operand can't be null, so the right operand is never executed.
Try removing the operator and the right operand.dartdead_null_aware_expression
The variable "name" won't be NULL because you give to him the value "Abdulelah", so the right part ?? "This is NULL" won't be executed, remove this right part and the warning will disappear.
Using ?? we provide default value in null case.
a = x ?? y
The above example shows that if x return/becomes null, y will be initialized on a. The fact becomes.
if x is not null, then a = x
if x is null, then a = y
Instead of using if, else we use ?? to provide null handler value.
The editor is acting smart here because it knows that name is not null, so the yellow message is saying you don't need to provide default value because left expression will never be null.
To create null variable, you need to use
DataType? variableName;
In this case you are initializing String and you can do
String? name = "Abdulelah";
But this is not needed unless you want to initialize null value on name variable.
You can check
Difference between var and dynamic type in Dart?
and dart.dev for more.

how to convert string to time formatted in flutter

I have data from database "192624". how I can change the String format in flutter become time formatted. example "192624" become to "19:26:24". I try using intl packages is not my hope result.
this my code
DateTime inputDate = inputDate;
String formattedTime = DateFormat.Hms().format(inputDate);
in above is not working
I want result convert data("192624") to become "19:26:24". data time from database.
use this method
String a() {
var a = "192624".replaceAllMapped(
RegExp(r".{2}"), (match) => "${match.group(0)}:");
var index = a.lastIndexOf(":");
a = a.substring(0,index);
return a;
}
Have you checked out this a answer :
String time;
// call this upper value globally
String x = "192624";
print(x.length);
x = x.substring(0, 2) + ":" + x.substring(2, 4)+":"+x.substring(4,x.length);
time =x;
print(x);
just globally declare the string and then assign the local String to global then call it in the ui

How to convert string in JSON to int Swift

self.event?["start"].string
The output is = Optional("1423269000000")
I want to get 1423269000000 as an Int
How can we achieve this? I have tried many ways such NSString (but it changed the value)
Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647. This may cause unexpected casting value. For more information, check this out: Numeric Types.
Try to run this code:
let maxIntegerValue = Int.max
println("Max integer value is: \(maxIntegerValue)")
In iPhone 4S simulator, the console output is:
Max integer value is: 2147483647
And iPhone 6 simulator, the console output is:
Max integer value is: 9223372036854775807
This information may help you.
But normally to convert Int to String:
let mInt : Int = 123
var mString = String(mInt)
And convert String to Int:
let mString : String = "123"
let mInt : Int? = mString.toInt()
if (mInt != null) {
// converted String to Int
}
Here is my safe way to do this using Optional Binding:
var json : [String:String];
json = ["key":"123"];
if var integerJson = json["key"]!.toInt(){
println("Integer conversion successful : \(integerJson)")
}
else{
println("Integer conversion failed")
}
Output:
Integer conversion successful :123
So this way one can be sure if the conversion was successful or not, using Optional Binding
I'm not sure about your question, but say you have a dictionary (Where it was JSON or not) You can do this:
var dict: [String : String]
dict = ["key1" : "123"]
var x : Int
x = dict["key1"].toInt()
println(x)
Just in case someone's still looking for an updated answer, here's the Swift 5+ version:
let jsonDict = ["key": "123"];
// Validation
guard let value = Int(jsonDict["key"]) else {
print("Error! Unexpected value.")
return
}
print("Integer conversion successful: \(value)")
// Prints "Integer conversion successful: 123"

Javascript create a function that returns a boolean value based on certain parameters

Thanks for taking the time to look at my problem. What I'm trying to do is create a javascript function that tests whether a sting is a particular length and also whether each element of that string can be found in another string. The function then needs to return a boolean value of either true or false depending on whether the string is valid.
Here's what I have:
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
function isValidGuess(inStr)
{ var valid;
var Str = inStr;
for (i=0; i<Str.length; i++)
{ if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES.length)
{ valid = true;
}
else
{ valid = false;
}
}
return valid;
}
This code is not working at all. It only returns false every time. Any help you could provide would be greatly appreciated. Thank you.
N_CHOICES.length return undefined, because variable N_CHOICES is number.
you have to change your condition to
if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES)