我是 Providers 的新手,我很享受它的相对快速和简单。
但是,我在当前正在构建的应用程序中遇到了问题。
这是一个简单的应用程序,可以获取物品、用户和他/她的购物车。
显示用户的信息、购物车和获取物品都很好。问题是当我想将一个项目添加到购物车时:我成功地将它添加到数据库中,但 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);
});
}
});
})
],
));
}
}
如何使每次呈现购物车页面时都从数据库中获取数据?