Home > database >  The argument type 'String?' can't be assigned to the parameter type 'String'
The argument type 'String?' can't be assigned to the parameter type 'String'

Time:12-27

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"

CodePudding user response:

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 :

Future<Column> makeCards() async {
  List<CryptoCard> cryptoCards = [];
  for (String crypto in cryptoList) {
    cryptoCards.add(
      CryptoCard(
        cryptoCurrency: crypto,
        selectedCurrency: selectedCurrency,
        value: isWaiting || coinValues[crypto] == null ? '?' : coinValues[crypto]!,
      ),
    );
  }
  return Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: cryptoCards,
  );
}

CodePudding user response:

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] with print(coinValues[crypto]) to make sure it is what you want. You can add a default value it will use if coinValues[crypto] is null like this: isWaiting ? '?' : coinValues[crypto] ?? "Empty", with "Empty" being the default value. or, make the value parameter of CryptoCard nullable. Basically, you are getting a null value from the CoinData service/API.

CodePudding user response:

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 ??

  • Related