我正在从Auth传递身份验证令牌。dart文件到产品。dart文件使应用程序能够获取我数据库中的产品,但应用程序无法获取这些,我是很新的扑动任何帮助将不胜感激
谢谢
这是我的Auth。飞镖文件
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import '../models/http_exceptions.dart';
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String _userId;
bool get isAuth {
return token != null;
}
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=<key>',
);
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 HttpEception(responseData['error']['message']);
}
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now().add(
Duration(
seconds: int.parse(responseData['expiresIn']),
),
);
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> signup(String email, String password) async {
return _authenticate(email, password, 'signUp');
}
Future<void> login(String email, String password) async {
return _authenticate(email, password, 'signInWithPassword');
}
}
这是我的产品。dart文件,该文件的Product类为
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shop_app/models/http_exceptions.dart';
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
@required this.id,
@required this.title,
@required this.description,
@required this.price,
@required this.imageUrl,
this.isFavorite = false,
});
Future<void> toggleFavoriteStatus() async {
final url = Uri.https(
'<confedential>.firebaseio.com',
'/products/$id.json',
);
final oldStatus = isFavorite;
isFavorite = !isFavorite;
notifyListeners();
final response = await http.patch(
url,
body: json.encode(
{
'isFavorite': isFavorite,
},
),
);
if (response.statusCode >= 400) {
isFavorite = oldStatus;
notifyListeners();
throw HttpEception('Could Not Change To Favourite');
}
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shop_app/models/http_exceptions.dart';
import './product.dart';
class Products with ChangeNotifier {
List<Product> _items = [];
final String authToken;
Products(this.authToken,this._items);
List<Product> get items {
return [..._items];
}
List<Product> get favoriteItems {
return _items.where((prodItem) => prodItem.isFavorite).toList();
}
Product findById(String id) {
return _items.firstWhere((prod) => prod.id == id);
}
Future<void> fetchAndSetProducts() async {
final url = Uri.https(
'<details>.firebaseio.com',
'/products.json?auth=$authToken',
);
try {
final response = await http.get(url);
// print(json.decode(response.body));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
final List<Product> loadedProducts = [];
extractedData.forEach((productId, productData) {
loadedProducts.add(
Product(
id: productId,
title: productData['title'],
description: productData['description'],
price: productData['price'],
isFavorite: productData['isFavourite'],
imageUrl: productData['imageUrl'],
),
);
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> addProduct(Product product) async {
var url = Uri.https(
'<details>.firebaseio.com',
'/products.json',
);
try {
final response = await http.post(
url,
body: json.encode(
{
'title': product.title,
'description': product.description,
'imageUrl': product.imageUrl,
'price': product.price,
'isFavourite': product.isFavorite,
},
),
);
final newProduct = Product(
title: product.title,
description: product.description,
price: product.price,
imageUrl: product.imageUrl,
id: json.decode(response.body)['name'],
);
_items.add(newProduct);
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> updateProduct(String id, Product newProduct) async {
final prodIndex = _items.indexWhere((prod) => prod.id == id);
if (prodIndex >= 0) {
final url = Uri.https(
'<details>.firebaseio.com',
'/products/$id.json',
);
http.patch(
url,
body: json.encode(
{
'title': newProduct.title,
'description': newProduct.description,
'imageUrl': newProduct.imageUrl,
'price': newProduct.price,
},
),
);
_items[prodIndex] = newProduct;
notifyListeners();
} else {
print('...');
}
}
Future<void> deleteProduct(String id) async {
final url = Uri.https(
'<details>.firebaseio.com',
'/products/$id.json',
);
final exisitingProductIndex = _items.indexWhere((prod) => prod.id == id);
var exisitingProduct = _items[exisitingProductIndex];
_items.removeAt(exisitingProductIndex);
notifyListeners();
final response = await http.delete(url);
if (response.statusCode >= 400) {
_items.insert(exisitingProductIndex, exisitingProduct);
notifyListeners();
throw HttpEception('Could Not Delete Product.');
}
exisitingProduct = null;
}
}
最后是main。Dart文件使用了所有这些
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './providers/auth.dart';
import './screens/cart_screen.dart';
import './screens/products_overview_screen.dart';
import './screens/product_detail_screen.dart';
import './providers/products.dart';
import './providers/cart.dart';
import './providers/orders.dart';
import './screens/orders_screen.dart';
import './screens/user_products_screen.dart';
import './screens/edit_product_screen.dart';
import './screens/auth_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
// Defining these providers for lisening to changes in the data
providers: [
ChangeNotifierProvider.value(
value: Auth(),
),
// First parameter is the type of data that we depened on and second is the data that we arre passing
ChangeNotifierProxyProvider<Auth, Products>(
update: (ctx, auth, previousProducts) => Products(
auth.token,
previousProducts == null ? [] : previousProducts.items,
),
),
ChangeNotifierProvider.value(
value: Cart(),
),
ChangeNotifierProvider.value(
value: Orders(),
),
],
child: Consumer<Auth>(
builder: (context, auth, _) => MaterialApp(
title: 'MyShop',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.deepOrange,
fontFamily: 'Lato',
),
// home: ProductsOverviewScreen(),
home: auth.isAuth ? ProductsOverviewScreen() : AuthScreen(),
routes: {
ProductDetailScreen.routeName: (ctx) => ProductDetailScreen(),
CartScreen.routeName: (ctx) => CartScreen(),
OrdersScreen.routeName: (ctx) => OrdersScreen(),
UserProductsScreen.routeName: (ctx) => UserProductsScreen(),
EditProductScreen.routeName: (ctx) => EditProductScreen(),
},
),
),
);
}
}
刚刚添加了create到ChangeNotifierProxyProvider
ChangeNotifierProxyProvider<Auth, Products>(
create: (_)=>Products('',[]),
update: (ctx, auth, previousProducts) => Products(
auth.token,
previousProducts == null ? [] : previousProducts.items,
),
),
并更改了product中的url字符串。飞镖文件
Uri url = Uri.parse(
'https://<some_details>.firebaseio.com/products.json?auth=$authToken');