Want compare string type variable in if condition how I do that
code
void ageCa() {
String age = widget.duration;
if (age > "Years: 2, Months: 00, Days: 00") {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(),
));
}
}
CodePudding user response:
As long, you use the current format, you can follow this. Also, I'm using 365 days in a year and 30 days on month, Or just use in days instead of duration
void ageCa() {
String age = widget.duration;
final data = age.split(",");
final List<int> numbers =
data.map((e) => int.parse(e.replaceAll(RegExp('[^0-9]'), ''))).toList();
//format "Years: 2, Months: 00, Days: 00"; only work on this format
Duration ageDuration =
Duration(days: numbers[0] * 365 numbers[1] * 30 numbers[2]);
if (ageDuration >= const Duration(days: 2 * 365)) {
} else {}
}
CodePudding user response:
Welcome, you can't check if condtion int value with string. It is programmaticaly incorrect to compare two different types.
void ageCa() {
String age = int.parse(widget.duration);// you need to change this string value
//to int like this
int val = 3; // you should change `"Years: 2, Months: 00, Days: 00"` to int
if (age > val) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(),
));
}
}