Quantcast
Channel: why do i get error of Undefined name even when the variable is defined? - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Moaz El-sawaf for why do i get error of Undefined name even when the variable is defined?

$
0
0

The Second Snippet will not work because you are not handling the return if the productId is null, so you have to always return something at the build() method.

For the First Snippet, the problem is that the variable called loadedProduct is defined inside the if condition block, which is not accessed outside its scope, to solve the problem you can do the following steps:

  1. Define the variable loadedProduct outside the if condition but not as final, e.g. var loadedProduct;
  2. Inside the if condition set the value of the variable, e.g. loadedProduct = Provider.of<Products>(context) ...
  3. By now, you have solved the problem if the productId is not null, but what if it is null?, then you have to think about the UI at this case, you can simply set a default title if the productId is null to better understand the case, e.g. Text(loadedProduct?.title ?? 'No Product Found')

NOTE:

loadedProduct?.title ?? 'No Product Found'

is equivalent to the following:

loadedProduct != null ? loadedProduct.title : 'No Product Found'

Viewing all articles
Browse latest Browse all 4

Trending Articles