Estou recebendo o erro acima no flutter versão 2.5.3, e isso está acontecendo quando tento fazer logout. Aparentemente, o erro tem algo a ver com o Products Provider, assim como o erro está mostrando. Mas ainda não consigo consertar. Também pode ter algo a ver com null safety, e como não estou muito familiarizado com isso, posso estar perdendo alguma coisa.
> The following _CastError was thrown building _InheritedProviderScope<Products?>(dirty, dependencies: [_InheritedProviderScope<Auth?>], value: Instance of 'Products',
> listening to value):
> Null check operator used on a null value
The relevant error-causing widget was ChangeNotifierProxyProvider<Auth, Products>
main.dart
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => Auth()),
ChangeNotifierProxyProvider<Auth, Products>(
update: (context, auth, previousProducts) => Products(auth.token!, auth.userId,
previousProducts == null ? [] : previousProducts.items),
create: (_) => Products('', '', []),
),
ChangeNotifierProvider(create: (context) => Cart()),
ChangeNotifierProxyProvider<Auth, Orders>(
update: (context, auth, previousOrders) => Orders(auth.token!,
previousOrders == null ? [] : previousOrders.orders, auth.userId),
create: (_) => Orders('', [], ''),
),
],
child: Consumer<Auth>(
builder: (context, authData, child) => MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
fontFamily: 'Lato',
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.purple)
.copyWith(secondary: Colors.deepOrange),
),
home: authData.isAuth ? ProductsOverviewScreen() : AuthScreen(),
//routes
),
));
auth.dart
class Auth with ChangeNotifier {
String? _token;
DateTime? _expiryDate;
String? _userId;
bool get isAuth {
return token != null;
}
String get userId {
return _userId!;
}
String? get token {
if (_expiryDate != null &&
_expiryDate!.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Future<void> _authenticate(
String email, String password, String urlSegment) async {
final url = Uri.parse(
"https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=AIzaSyAA9PShE7c2ogk5L13kI0mgw24HKqL72Vc");
try {
final response = await http.post(url,
body: json.encode({
'email': email,
'password': password,
'returnSecureToken': true
}));
final responseData = json.decode(response.body);
if (responseData['error'] != null) {
throw HttpException(responseData['error']['message']);
}
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now()
.add(Duration(seconds: int.parse(responseData['expiresIn'])));
} catch (error) {
throw error;
}
notifyListeners();
}
Future<void> logout() async {
_token = null;
_userId = null;
_expiryDate = null;
notifyListeners();
}
}