0

Prior to migrating to null safety this worked. This is a user login verification method.

Future<bool> loginValidate() async {
    final String dir = await getDocDir(); //getting documents directory
    try {
      await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }
      });
    } on FileSystemException {
      //invalid username
      return Future<bool>.value(false);
    } catch (e) {
      return Future<bool>.value(false);
    }
    //success
    return Future<bool>.value(true);
  }

This error occurs when the app is being built.

I believe it has to do with the anonymous function argument within the .then() method.

Demiurge
  • 3
  • 2
  • 2
    Your callback function neglects to return a value along all code paths. Therefore, it implicitly returns `null` along if the `if` condition isn't met, and a `null` return value is unexpected. Fix your code to return values along all code paths. Also, it's inconsistent to mix `await` and `then`; just use `await`, which would have made your problem more obvious. – jamesdlin Sep 09 '21 at 08:00

2 Answers2

1

You need to return the await function and also need to set the true value to make it work:

return await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }

        //Also need this code as it will return null if not set
        return Future<bool>.value(true);
      });

BETTER WAY I THINK:

Let's change this code:

await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }
      });

to this:

String contents = await File('$dir/$_userLoginString.json').readAsString();
final json = jsonDecode(contents) as Map<String, dynamic>;
final user = PersonLoginJson.fromJson(json);
if (_userPasswordString != user.password) {
   //invalid password
   return Future<bool>.value(false);
}

Then it will be easier to debug your code now.

Lam Thanh Nhan
  • 486
  • 4
  • 5
0
if (_userPasswordString != user.password) {
  //invalid password
  return Future<bool>.value(false);
} else {
  return Future<bool>.value(true);   // <--- here needed
}
JerryZhou
  • 4,566
  • 3
  • 37
  • 60