1

Class AddProduct.dart

class _AddProductState extends State<AddProduct> {
  CategoryService _categoryService = CategoryService();
  BrandService _brandService = BrandService();
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  TextEditingController prodoctNameController = TextEditingController();
  List<DocumentSnapshot> brands = <DocumentSnapshot>[];
  List<DocumentSnapshot> categories = <DocumentSnapshot>[];
  List<DropdownMenuItem<String>> categoriesDropDown =
      <DropdownMenuItem<String>>[];
  List<DropdownMenuItem<String>> brandsDropDown = <DropdownMenuItem<String>>[];
  String _currentCategory = "test";
  String _brandCategory;
  Color white = Colors.white;
  Color black = Colors.black;
  Color grey = Colors.grey;
  Color blue = Colors.blue;

  @override
  void initState() {
    _getCategories();
    //_getBrands();
    categoriesDropDown = getCategoriesDropDown();
    //_currentCategory = categoriesDropDown[0].value;
  }

  List<DropdownMenuItem<String>> getCategoriesDropDown() {
    List<DropdownMenuItem<String>> items = new List();
    for (DocumentSnapshot category in categories) {
      items.add(new DropdownMenuItem(
        child: Text(category['category']),
        value: category['category'],
      ));
    }
    return items;
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: white,
        leading: Icon(
          Icons.close,
          color: black,
        ),
        title: Text(
          "Añadir producto",
          style: TextStyle(color: black),
        ),
      ),
      body: Form(
        key: _formKey ?? '',
        child: ListView(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: OutlineButton(
                      borderSide:
                          BorderSide(color: grey.withOpacity(0.8), width: 1.0),
                      onPressed: () {},
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(14, 40, 14, 40),
                        child: new Icon(
                          Icons.add,
                          color: grey,
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: OutlineButton(
                      borderSide:
                          BorderSide(color: grey.withOpacity(0.8), width: 1.0),
                      onPressed: () {},
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(14, 40, 14, 40),
                        child: new Icon(
                          Icons.add,
                          color: grey,
                        ),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: OutlineButton(
                      borderSide:
                          BorderSide(color: grey.withOpacity(0.8), width: 1.0),
                      onPressed: () {},
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(14, 40, 14, 40),
                        child: new Icon(
                          Icons.add,
                          color: grey,
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Indicar nombre del producto',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: blue,
                  fontSize: 12,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: TextFormField(
                controller: prodoctNameController,
                decoration: InputDecoration(hintText: "Añadir nombre producto"),
                // ignore: missing_return
                validator: (value) {
                  if (value.isEmpty ?? "") {
                    return 'Por favor, introduzca el nombre';
                  } else if (value?.length ?? 0 > 10) {
                    return 'No se puede tener mas de 10 letras';
                  }
                },
              ),
            ),
            Center(
              child: DropdownButton(
                  value: _currentCategory,
                  items: categoriesDropDown,
                  onChanged: changeSelectedCategory),
            )
          ],
        ),
      ),
    );
  }

  _getCategories() async {
    List<DocumentSnapshot> data = await _categoryService.getCategories();
    print(data.length);
    setState(() {
      categories = data;
    });
    if (_getCategories() == true) {
      return categories;
    } else {
      return categories.length;
    }
  }

  changeSelectedCategory(String selectedCategory) {
    setState(() => _currentCategory = selectedCategory);
  }
}

Categories.dar class

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:uuid/uuid.dart';
 
class CategoryService {
  // ignore: deprecated_member_use
  FirebaseFirestore _firestore = FirebaseFirestore.instance;
  String ref = 'categories';
 
  void createCategory(String name) {
    var id = Uuid();
    String categoryId = id.v1();
 
    _firestore.collection(ref).document(categoryId).setData({'category': name});
  }
 
  Future<List<DocumentSnapshot>> getCategories() =>
      _firestore.collection(ref).getDocuments().then((snaps) {
        snaps.documents;
      });
 
  Future<List<DocumentSnapshot>> getSuggestions(String suggestion) => _firestore
          .collection(ref)
          .where('category', isEqualTo: suggestion)
          .getDocuments()
          .then((snap) {
        print(snap.documents.length);
        return snap.documents;
      });
}

And the error is this: Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length) Please, con you help me? I don't know what can I do, I've been trying to fix it for days. I need tu add this at farebase, but i can´t for this error ¿Any idea?

Daniel loaiza
  • 105
  • 1
  • 2
  • 8
  • 2
    Your question should identify which line of code causes that error, and what you're doing that causes it. There should be enough information in your question so that anyone can copy it and observe the same result. – Doug Stevenson Oct 24 '20 at 05:28

0 Answers0