Reputation: 101
I'm getting the 'null check operator used on a null value' when I try to access specific screens.
I blocked out my 'user_provider' custom class as well as parts of the code where it's used and it displays normally (no red screen) but without those screens.
This is the custom class
import 'package:flutter/widgets.dart';
import 'package:purple/models/user.dart';
import 'package:purple/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
I underdertand this could be as a result of the bang operator in line 9 but I'm new to fluttr and have no idea how to go about it.
Upvotes: 5
Views: 806
Reputation: 619
You should not call getUser
if it returns null. Maybe you did not load the user from _authMethods.getUserDetails()
.
So here is an idea, check if user is logged in first then call getUser
import 'package:flutter/widgets.dart';
import 'package:purple/models/user.dart';
import 'package:purple/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
bool get isLoggedIn => _user != null; // <---------- added
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
then in a screen or a widget:
if (userProvider.isLoggedIn) {
// TODO: do what you want such as returning user's name
return userProvider.getUser.name;
}
Upvotes: 1
Reputation: 4556
Try this:
import 'package:flutter/widgets.dart';
import 'package:purple/models/user.dart';
import 'package:purple/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
Upvotes: 0