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
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:
The issue is you’re tying to add value in
age
variable which is not assigned yet,You can either make the
age
variable aslate 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: