skip to Main Content

I want to show a_page if the ageValue value is less than 13, b_page if it is less than 15, and c_page if it is less than 17

final ageValue = 0;
final age;
if(ageValue <= 17){
   age = const c_page;
} else if(ageValue <= 15{
   age = const b_page;
} else if(ageValue <= 13{
   age = const a_page;
} else {

}

If you use age after that, you will get the following error

error The final variable 'age' can't be read because it's potentially unassigned at this point. (Documentation) Ensure that it is assigned on necessary execution paths.

If you give me an if statement according to the ageValue, the age changes, and I thought that using age would allow me to take and use custom widgets without any major problems. But it was wrong and I couldn’t find a way.

2

Answers


  1. in dart language when you define a final variable, you should initialize it at compile time, but you can late it, late means that you will initialize it at runtime before first call, try this code:

    final ageValue = 0;
    late final Widget age;
    if(ageValue <= 17){
    age = const c_page;
    } else if(ageValue <= 15{
    age = const b_page;
    } else if(ageValue <= 13{
    age = const a_page;
    } else {
    
    }
    
    Login or Signup to reply.
  2. The issue is you’re tying to add value in age variable which is not assigned yet,

    You can either make the age variable as late final so we are assuring the compiler that this variable will be assigned in the future.
    Or Remove the final and add some initialise value to it.

    And going through your code i can see your conditions are also wrong; See we take your code and assume ageValue is 12 then it goes to the first condition which is ageValue <= 17 which is true, 12 < 17 is true so the a_page will be shown which wrong, it should show the c_page.

    So It should be like below:

      final ageValue = 0;
      late final age;
    
      if (ageValue <= 13) {
        age = c_page;
      } else if (ageValue <= 15) {
        age = b_page;
      } else if (ageValue <= 17) {
        age = a_page;
      } else {
        
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search