Laurent
Laurent

Reputation: 741

compilation error on dart/flutter with null safety

I have 2 classes A: with the function

  static Future<bool> setToken(String? value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(_kToken, value);
  }

and B which is called by A

  Future<bool> setString(String key, **String? value**) =>
      _setValue('String', key, value);

in A, the parameter 'value' is underlined and I have a compilation error on

prefs.setString('token', value);

The argument type 'String?' can't be assigned to the parameter type 'String'.

However I writed String**?** value on setString in B class ...?

Help me please.

Upvotes: 0

Views: 198

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63769

setString required non-nullable string data,

  Future<bool> setString(String key, String value) =>
      _setValue('String', key, value);

you can avoid putting data while it is null.

Future<bool> setToken(String? value) async {
  if (value == null) return false;

  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.setString("_kToken", value);
}

Upvotes: 1

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12703

Remove the ? because setString expects a non-null value.

  static Future<bool> setToken(String value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(_kToken, value);
  }

Upvotes: 0

Related Questions