1

Want compare string type variable in if condition how I do that

enter image description here

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(),
          ));
    }
  }
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
Dasun Dola
  • 541
  • 2
  • 16

2 Answers2

0

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(),
      ));
}

}

brook yonas
  • 436
  • 3
  • 14
0

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 {}
  }
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56