NoSuchMethodError(NoSuchMethodError:对null调用了getter'length'。Receiver:null尝试调用:length)

时间:2020-10-24 05:04:39

标签: android firebase flutter dart

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类

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;
      });
}

错误是这样的:发生异常。 NoSuchMethodError(NoSuchMethodError:在null上调用了获取方法“长度”。接收方:null尝试在调用方法:length)请帮您帮助我吗?我不知道该怎么办,我已经尝试了好几天了。我需要在farebase上添加此文件,但我无法解决此错误吗?

0 个答案:

没有答案