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
loadedProductoutside theif conditionbut not asfinal, e.g. var loadedProduct; - Inside the
if conditionset the value of the variable, e.g.loadedProduct = Provider.of<Products>(context) ... - By now, you have solved the problem if the
productIdis notnull, but what if it isnull?, then you have to think about theUIat this case, you can simply set a defaulttitleif theproductIdisnullto 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'