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:
- Define the variable
loadedProduct
outside theif condition
but not asfinal
, e.g. var loadedProduct; - Inside the
if condition
set the value of the variable, e.g.loadedProduct = Provider.of<Products>(context) ...
- By now, you have solved the problem if the
productId
is notnull
, but what if it isnull
?, then you have to think about theUI
at this case, you can simply set a defaulttitle
if theproductId
isnull
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'