使用 Providers 设置页面状态后如何重建页面?
How can I rebuild a page after setting its state with Providers?
我是 Providers 的新手,我很喜欢它相对快速和简单。
但是,我在构建的应用程序中遇到了问题。
这是一个简单的应用程序,可以获取项目、用户和 his/her 购物车。
显示用户的信息、购物车和获取项目都很好。问题是当我想将商品添加到购物车时:我已成功将其添加到数据库,但 UI 没有改变。 UI 应用完全重启后更新
购物车页面
import 'package:coolkicks/providers/user-provider.dart';
import 'package:coolkicks/shared/cartItems.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Cart extends StatefulWidget {
@override
_CartState createState() => _CartState();
}
class _CartState extends State<Cart> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
Future.delayed(Duration.zero, () {
Provider.of<UserProvider>(context, listen: false).fetchTheUser();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[],
title: Text('Cart'),
),
body:
Consumer<UserProvider>(
builder: (context, model, child) {
if (model.isLoading) {
return Center(child: CircularProgressIndicator());
} else {
return CartItems();
}
},
),
);
}
}
加入购物车页面
import 'package:coolkicks/models/product.dart';
import 'package:coolkicks/providers/product-provider.dart';
import 'package:coolkicks/providers/user-provider.dart';
import 'package:coolkicks/screens/cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class DetailsPage extends StatefulWidget {
final Product product;
DetailsPage({this.product});
@override
_DetailsPageState createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
bool loading = false;
@override
Widget build(BuildContext context) {
final Map<String, dynamic> user =
Provider.of<UserProvider>(context, listen: false).user;
Map<String, String> data;
if (user != null) {
data = {
"shoeId": widget.product.shoeId,
"shoeSize": "32",
"email": user['user'].email
};
}
return Scaffold(
backgroundColor: Colors.blue[100],
appBar: AppBar(
elevation: 0.0,
title: Text('Details'),
),
body: Column(
children: <Widget>[
Card(
margin: EdgeInsets.fromLTRB(20.0, 6.0, 20.0, 0.0),
child: ListTile(
trailing: Text('Ksh. ${widget.product.price.toString()}'),
leading: CircleAvatar(
radius: 25.0,
backgroundImage: AssetImage('assets/shoe.jpg')),
title: Text(widget.product.title),
subtitle: Text(widget.product.description),
),
),
SizedBox(height: 50.0),
Consumer<ProductProvider>(builder: (context, model, child) {
return loading ? CircularProgressIndicator() : RaisedButton(
child: Text('Add to Cart'),
onPressed: () async {
setState(() {
loading = true;
});
if (user == null) {
return print('Login to add to cart');
} else {
return model.addToCart(data)
.then((value) => {
setState(() {
loading = false;
}),
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => Cart()))
})
.catchError((err) {
print(err);
});
}
});
})
],
));
}
}
如何做到每次渲染购物车页面时,都从数据库中获取数据?
我找到问题了
这是一个相当愚蠢的
在我的 UserProvider 中,在获取购物车时,我没有考虑到用户不是空的。注释掉 if 检查后,它起作用了。我将不得不重新考虑我检查用户的方式
Future fetchTheUser() async {
final Map<String, User> fetchedUser = {};
final List<Cart> fetchedCart = [];
// if (_user.isEmpty) {
_isLoading = true;
notifyListeners();
final Map<String, dynamic> userData =
await getProfile().catchError((error) => {_isLoading = true});
if (userData == null) {
return _user = null;
} else {
final theUser = User(
firstname: userData['firstname'],
lastname: userData['lastname'],
email: userData['email'],
cart: userData['cart']);
fetchedUser['user'] = theUser;
_user = fetchedUser;
final Map<String, dynamic> cartData = userData['cart'];
cartData['items'].forEach((dynamic cartItem) {
final Cart cart = Cart(
productId: cartItem['productId'],
item: cartItem['item'],
qty: cartItem['qty'],
price: cartItem['price'],
totalPrice: cartData['totalPrice'],
totalQty: cartData['totalQty']
);
fetchedCart.add(cart);
});
_cart = fetchedCart;
_isLoading = false;
notifyListeners();
}
// } else {
// _user = _user;
// notifyListeners();
// }
}
我是 Providers 的新手,我很喜欢它相对快速和简单。
但是,我在构建的应用程序中遇到了问题。
这是一个简单的应用程序,可以获取项目、用户和 his/her 购物车。
显示用户的信息、购物车和获取项目都很好。问题是当我想将商品添加到购物车时:我已成功将其添加到数据库,但 UI 没有改变。 UI 应用完全重启后更新
购物车页面
import 'package:coolkicks/providers/user-provider.dart';
import 'package:coolkicks/shared/cartItems.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Cart extends StatefulWidget {
@override
_CartState createState() => _CartState();
}
class _CartState extends State<Cart> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
Future.delayed(Duration.zero, () {
Provider.of<UserProvider>(context, listen: false).fetchTheUser();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[],
title: Text('Cart'),
),
body:
Consumer<UserProvider>(
builder: (context, model, child) {
if (model.isLoading) {
return Center(child: CircularProgressIndicator());
} else {
return CartItems();
}
},
),
);
}
}
加入购物车页面
import 'package:coolkicks/models/product.dart';
import 'package:coolkicks/providers/product-provider.dart';
import 'package:coolkicks/providers/user-provider.dart';
import 'package:coolkicks/screens/cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class DetailsPage extends StatefulWidget {
final Product product;
DetailsPage({this.product});
@override
_DetailsPageState createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
bool loading = false;
@override
Widget build(BuildContext context) {
final Map<String, dynamic> user =
Provider.of<UserProvider>(context, listen: false).user;
Map<String, String> data;
if (user != null) {
data = {
"shoeId": widget.product.shoeId,
"shoeSize": "32",
"email": user['user'].email
};
}
return Scaffold(
backgroundColor: Colors.blue[100],
appBar: AppBar(
elevation: 0.0,
title: Text('Details'),
),
body: Column(
children: <Widget>[
Card(
margin: EdgeInsets.fromLTRB(20.0, 6.0, 20.0, 0.0),
child: ListTile(
trailing: Text('Ksh. ${widget.product.price.toString()}'),
leading: CircleAvatar(
radius: 25.0,
backgroundImage: AssetImage('assets/shoe.jpg')),
title: Text(widget.product.title),
subtitle: Text(widget.product.description),
),
),
SizedBox(height: 50.0),
Consumer<ProductProvider>(builder: (context, model, child) {
return loading ? CircularProgressIndicator() : RaisedButton(
child: Text('Add to Cart'),
onPressed: () async {
setState(() {
loading = true;
});
if (user == null) {
return print('Login to add to cart');
} else {
return model.addToCart(data)
.then((value) => {
setState(() {
loading = false;
}),
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => Cart()))
})
.catchError((err) {
print(err);
});
}
});
})
],
));
}
}
如何做到每次渲染购物车页面时,都从数据库中获取数据?
我找到问题了
这是一个相当愚蠢的
在我的 UserProvider 中,在获取购物车时,我没有考虑到用户不是空的。注释掉 if 检查后,它起作用了。我将不得不重新考虑我检查用户的方式
Future fetchTheUser() async {
final Map<String, User> fetchedUser = {};
final List<Cart> fetchedCart = [];
// if (_user.isEmpty) {
_isLoading = true;
notifyListeners();
final Map<String, dynamic> userData =
await getProfile().catchError((error) => {_isLoading = true});
if (userData == null) {
return _user = null;
} else {
final theUser = User(
firstname: userData['firstname'],
lastname: userData['lastname'],
email: userData['email'],
cart: userData['cart']);
fetchedUser['user'] = theUser;
_user = fetchedUser;
final Map<String, dynamic> cartData = userData['cart'];
cartData['items'].forEach((dynamic cartItem) {
final Cart cart = Cart(
productId: cartItem['productId'],
item: cartItem['item'],
qty: cartItem['qty'],
price: cartItem['price'],
totalPrice: cartData['totalPrice'],
totalQty: cartData['totalQty']
);
fetchedCart.add(cart);
});
_cart = fetchedCart;
_isLoading = false;
notifyListeners();
}
// } else {
// _user = _user;
// notifyListeners();
// }
}