0

Android Studio throws this following NullSafety error on split in Flutter.

The method 'split' can't be unconditionally invoked because the receiver can be 'null'.  Try making the call conditional (using '?.') or adding a null check to the target ('!'). Open documentation 

But none of the suggested fixes work. Heres' the code;

FutureBuilder(
      future: jwtOrEmpty,
      builder: (context, snapshot) {
        if(!snapshot.hasData) return CircularProgressIndicator();
        if(snapshot.data != "") {
          var str = snapshot.data;
          var jwt = str.split(".");

          if(jwt.length !=3) {
            return LoginPage();
          } else {
            var payload = json.decode(ascii.decode(base64.decode(base64.normalize(jwt[1]))));
            if(DateTime.fromMillisecondsSinceEpoch(payload["exp"]*1000).isAfter(DateTime.now())) {
              return HomePage(str, payload);
            } else {
              return LoginPage();
            }
          }
        } else {
          return LoginPage();
        }
      }
  ),

I'm guessing it's because the returned snapshot.data can't be null. But I'm not sure what I can do about it. I tried adding "!" and "?" to snapshot.data, str, jwt and splitbut nothing works.

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Meggy
  • 1,491
  • 3
  • 28
  • 63
  • `str?.split(".")` or `str?.split?.call(".")` should work or `str!.split(".")` if you are sure it's not null – casraf May 30 '21 at 12:36

2 Answers2

1

Although Android Studio said otherwise, it looks like the problem wasn't with Null safety but because "str" wasn't really a string. So I did this;

var str = snapshot.data;
var jwt = str.toString().split("."); 

Also, I had to add // @dart=2.9 to the top of the file as the flutter storage dependency does not support NULL SAFETY.

Meggy
  • 1,491
  • 3
  • 28
  • 63
0

What it is trying to say is that your str could be null because snapshot.data could be null.

So one way to use it would be,

var jwt = str!.split('.'); // This means we are saying that str will never be null.

But obviously, this would crash if str was actually null at runtime.

Better way to do it,

var str = snapshot.data;
var jwt = [];

if (str != null)
  jwt = str.split(".");

Assuming your snapshot.data is a string, this will never crash since we are putting a null check.

Nisanth Reddy
  • 5,967
  • 1
  • 11
  • 29