Caramel
Caramel

Reputation: 121

type 'String?' can't be assigned to type 'String'

Here's my code

Saving String to shared preference

if (croppedFile != null) {
      imageFile = croppedFile;
      final bytes = Io.File(imageFile!.path).readAsBytesSync();
      String img64 = base64Encode(bytes);
      setState(() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('image', img64);
      });
    }

Calling shared preference

SharedPreferences prefs = await SharedPreferences.getInstance();
                                var iMG = prefs.getString('image');

                                await DatabaseHelper.instance.add(
                                          Cards(
                                              name: NamaKartuController.text,
                                              desc: DescKartuController.text,
                                              iMG : iMG
                                          )
                                );

i set it as a String but it does still giving - The argument type 'String?' can't be assigned to the parameter type 'String Error

Upvotes: 0

Views: 379

Answers (2)

Lucas
Lucas

Reputation: 339

base64Encode(bytes) Can return null meaning it has a return type of String?, and not String.

Because String img64 isn't declared as a nullable variable, it will not accept a value of null. You can change the method call to base64Encode(bytes)!, which will assert if the returned value of base64Encode(bytes)! is null at runtime.

Simply adding .toString() to the existing code doesn't really deal with the issue, as if null is returned from the method, it'll just convert that to the string "null", which feels more like just getting the code to fail silently instead of fixing the issue.

https://dart.dev/codelabs/null-safety

Upvotes: 1

Rakesh Saini
Rakesh Saini

Reputation: 753

I think error is in this line. Try to convert this line into string as below-

String img64 = base64Encode(bytes).toString();

Please let me know the errr again?

Upvotes: 2

Related Questions