Method cartReference Returning Null (in my firebase has the Subcollection 'Cart', within the 'Users' Collection)

Asked

Viewed 42 times

-2

I’m days away with this problem, I’m making a delivery app, time to add the product to the cart, it tells me it’s returning Null the method cartReference, but when I click again on the button " add cart" he adds however does not send to Firebase and brings me problems up front, Follow below the codes

import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:suburbiodeliery/src/products.dart';

import 'package:suburbiodeliery/src/user_manager.dart';

import 'cart_manager.dart';
import 'itempagamentos.dart';

class ProductScreen extends StatelessWidget {
  final Products product;

  const ProductScreen(this.product);


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: product,
      child: Scaffold(
        appBar: AppBar(
          title: Text(product.name),
          centerTitle: true,
          actions: <Widget>[
            Consumer<UserManager>(
              builder: (_, userManager, __) {

                  return IconButton(
                    icon: Icon(Icons.edit),
                    onPressed: () {
                      Navigator.of(context)
                          .pushReplacementNamed('/edit_product');
                    },
                  );

              },
            )
          ],
        ),
        backgroundColor: Colors.white,
        body: ListView(
          children: <Widget>[
            AspectRatio(
              aspectRatio: 1,
              child: Carousel(
                images: product.images.map((url) {
                  return NetworkImage(url);
                }).toList(),
                dotSize: 4,
                dotSpacing: 15,
                dotBgColor: Colors.transparent,
                autoplay: false,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Text(
                    product.name,
                    style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w600,
                        color: Colors.black),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(
                      'A partir de',
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 18,
                      ),
                    ),
                  ),
                  Text(
                    product.price,
                    style: TextStyle(
                        fontSize: 22.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.green),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 16, bottom: 8),
                    child: Text(
                      'Descrição:',
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.black),
                    ),
                  ),
                  Text(
                    product.description,
                    style: const TextStyle(fontSize: 16, color: Colors.black),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 16, bottom: 8),
                    child: Text(
                      'Pagamentos:',
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.black),
                    ),
                  ),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: product.pagamentos.map((p) {
                      return PagamentosWidget(pagamentos: p);
                    }).toList(),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Consumer2<UserManager, Products>(
                    builder: (_, userManager, product, __) {
                      return SizedBox(
                        height: 44,
                        child: RaisedButton(
                            onPressed: product.selectedPagamentos != null
                                ? () {
                              context.read<CartManager>().addToCart(product);
                              Navigator.of(context).pushNamed('/cart_screen');
                                                       }
                                : null,
                            color: Colors.blue,
                            textColor: Colors.white,
                            child: Text('Adicionar ao Carrinho',
                                style: TextStyle(color: Colors.white))),
                      );
                    },
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

 //Aqui é onde chamo a colecction do firebase 

DocumentReference get firestoreRef =>Firestore.instance.document('users/$id');

  CollectionReference get cartReference => firestoreRef.collection('cart');



// Essa e a variavel que adiciona ao carrinho ( ou deveria ) 
    void addToCart(Products product) {
        try {
          final e = items.firstWhere((p) => p.stackable(product));
          e.increment();
        } catch (e) {
          final cartProduct = CartProduct.fromProduct(product);
          cartProduct.addListener(_onItemUpdated);
          items.add(cartProduct);
          user.cartReference
              .add(cartProduct.toCartItemMap())
              .then((doc) => cartProduct.id = doc.documentID);
          _onItemUpdated();
        }
        notifyListeners();
      }
// Esse é o Botão de Adicionar ao carrinho 

RaisedButton(
                            onPressed: product.selectedPagamentos != null
                                ? () {
                              context.read<CartManager>().addToCart(product);
                              Navigator.of(context).pushNamed('/cart_screen');
                                                       }
                                : null,
                            color: Colors.blue,
                            textColor: Colors.white,
                            child: Text('Adicionar ao Carrinho',
                                style: TextStyle(color: Colors.white))),

1 answer

0


Well come on, in pieces.

1. This is a function, not a variable:

void addToCart(Products product)

2. Have you read about Try-catch?

It serves to treat errors, for example:

try {
  Int valorTotal = 0;
  valorTotal = "Teste";
}
catch(e) {
  print("Erro $e"); //Erro "String" não é um Inteiro
}

You there in the example that we were given, made a wrong use, so the part that’s inside the catch{} will only work if error inside the try{}.

Amendments

Maybe doing it this way will solve your problems:

void addToCart(Products product) {
    try {
      final e = items.firstWhere((p) => p.stackable(product));
      e.increment();
    
      final cartProduct = CartProduct.fromProduct(product);
      cartProduct.addListener(_onItemUpdated);
      
      items.add(cartProduct);
      
      user.cartReference
          .add(cartProduct.toCartItemMap())
          .then((doc) {
            cartProduct.id = doc.documentID;
                      
            _onItemUpdated();
      
            notifyListeners();
          });
    
    } catch (e) {
        print("Exibie o erro ou o que tu quiser fazer $e");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.