This is my code
Map<String, String> coinValues = {};
bool isWaiting = false;
void getData() async {
isWaiting = true;
try {
var data = await CoinData().getCoinData(selectedCurrency);
isWaiting = false;
setState(() {
coinValues = data;
});
} catch (e) {
print(e);
}
}
Future<Column> makeCards() async {
List<CryptoCard> cryptoCards = [];
for (String crypto in cryptoList) {
cryptoCards.add(
CryptoCard(
cryptoCurrency: crypto,
selectedCurrency: selectedCurrency,
value: isWaiting ? '?' : coinValues[crypto],
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: cryptoCards,
);
}
I get the following error
Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
value: isWaiting ? '?' : coinValues[crypto],
I tried adding a null check but the app crash and says "Null check operator used on a null value"
3
Answers
It means that your coinValues[crypto] returns null.
You should check if coinValues[crypto] could be null or not.
Otherwise you can try the following code :
Adding a null check (!) is like telling the compiler that you know better and that the API data for
coinValues[crypto]
will not be null. However, if it is it will give that error. Try printing out the value of coinValues[crypto] withprint(coinValues[crypto])
to make sure it is what you want. You can add a default value it will use ifcoinValues[crypto]
is null like this:isWaiting ? '?' : coinValues[crypto] ?? "Empty"
, with "Empty" being the default value. or, make thevalue
parameter ofCryptoCard
nullable. Basically, you are getting a null value from the CoinData service/API.Error is caused by the null safety Dart, see https://dart.dev/null-safety.
The result of method CoinData().getCoinData(selectedCurrency); is String?, i.e. it may be a String, or it may be null. The widget (CryptoCard value:) requires a (non-null) String. You should check that the value is initialed, then you can assert that the value is non-null. Better still, you should use
And also this line have error value: isWaiting ? ‘?’ : coinValues[crypto],
you should using (or) shorthand ??