0

我是 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);
                      });
                    }
                  });
            })
          ],
        ));
  }
}

如何使每次呈现购物车页面时都从数据库中获取数据?

4

1 回答 1

0

我解决了这个问题。
这是一个相当愚蠢的在我的 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();
    // }
  }
于 2020-07-22T14:01:36.890 回答