'How to pass data from one model to another model using provider in flutter
Hello i was trying to pass the auth token from my auth model to product model. I have try the bellow code.
Auth Model Provider
String get token {
if (_expiryDate != null &&
_expiryDate!.isAfter(DateTime.now()) &&
_token != '') {
return _token!;
}
return '';
}
Product Model provider
String? authToken;
void update(authToken, items) {
_items = items;
authToken = authToken;
print(authToken);
notifyListeners();
}
Future<void> fetchAndSetProducts() async {
final url = Uri.parse(
'https://flutter-app-848b9-default-rtdb.firebaseio.com/products.json?auth=$authToken');
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<Product> loadedProducts = [];
extractedData.forEach((prodId, prodData) {
loadedProducts.add(Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
imageUrl: prodData['imageUrl'],
isFavorite: prodData['isFavorite'],
));
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
rethrow;
}
Main.dart file
ChangeNotifierProxyProvider<Auth, Products>(
create: (ctx) => Products(),
update: (ctx, auth, previousProducts) => previousProducts!
..update(auth.token,
previousProducts.items == null ? [] : previousProducts.items),
),
Once the widget is build i was able to print out the auth token but i can not pass it to the API param. Am new in Flutter and Dart.
Solution 1:[1]
Try these if you're working with flutter v2:
Auth Model Provider
String? get token {
if (_expiryDate != null &&
_expiryDate!.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Main.dart
...
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: Auth(),
),
ChangeNotifierProxyProvider<Auth, Products>(
create: (ctx) => Products('', '', []),
update: (ctx, auth, previousProducts) =>
Products(auth.token, auth.userId, previousProducts?.items ?? []),
),
ChangeNotifierProvider(
create: (ctx) => Cart(),
),
ChangeNotifierProxyProvider<Auth, Orders>(
create: (ctx) => Orders('', '', []),
update: (ctx, auth, previousOrders) =>
Orders(auth.token, auth.userId, previousOrders?.orders ?? []),
)
],
child: Consumer<Auth>(
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nonsocchi |
