【问题标题】:Flutter querysnapshot .getDocuments().then not executing functionFlutter querysnapshot .getDocuments().then 不执行函数
【发布时间】:2020-10-09 12:27:30
【问题描述】:

我在从 firebase 获取数据时遇到了一些问题并得到一个错误,我正在返回一个空值(见下图),因为我调试并执行了一些断点,看起来问题是,它没有执行.thenSEE HERE之后的代码

错误

而且我在这里使用提供程序包。

WIDGETCATEGORIES.DART

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

import '../global/custom.dart';

import '../provider/prv_category.dart';

class WidgetCategories extends StatefulWidget {
  @override
  _WidgetCategoriesState createState() => _WidgetCategoriesState();
}

class _WidgetCategoriesState extends State<WidgetCategories> {

  @override
  Widget build(BuildContext context) {

    RandomColor _randomColor = RandomColor();
    // final categoryCount =
    //     Provider.of<ProviderProducts>(context).getCategoryCount() > 0;
    final isNotNull = Provider.of<ProviderProducts>(context, listen: false)
            .categories
            .categoryDocumentData !=
        null;

    final category = Provider.of<ProviderProducts>(context);
    final _categories = category.categories.categoryDocumentData;

    return !isNotNull
        ? Center(
            child: CircularProgressIndicator(),
          )
        : Container(
            height: 115,
            //width: 90,
            child: ListView.builder(
              physics: BouncingScrollPhysics(),
              itemCount: _categories.length,
              scrollDirection: Axis.horizontal,
              //padding: EdgeInsets.all(1 0.0),
              itemBuilder: (context, i) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Card(
                      color: _randomColor.randomColor(
                        //colorSaturation: ColorSaturation.highSaturation,
                        colorBrightness: ColorBrightness.dark,
                      ),
                      semanticContainer: true,
                      clipBehavior: Clip.antiAliasWithSaveLayer,
                      child: Column(
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.only(
                              top: 13,
                              left: 15,
                              right: 15,
                            ),
                            child: Image.network(
                              _categories[i]['imgPath'],
                              height: 60,
                              width: 60,
                              fit: BoxFit.fill,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(
                              bottom: 10.0,
                            ),
                            child: CustTextBody(
                              cText: _categories[i]['category_name'],
                              cTxtStyle: Theme.of(context).textTheme.headline5,
                              cTxtAlign: TextAlign.center,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ));
  }
}

MODELCATEGORIES.dart

import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:flutter/material.dart';

class ModelCategories {
  List<Map<dynamic, dynamic>> _categoryDocumentData = [];

  // List<Map<dynamic, dynamic>> get categoryDocumentData => _categoryDocumentData;
  List<Map<dynamic, dynamic>> get categoryDocumentData {
    return [..._categoryDocumentData];
  }

  ModelCategories.fromSnapshot(QuerySnapshot snapshot) {
    _categoryDocumentData =
        snapshot.documents.map((DocumentSnapshot e) => e.data).toList();
  }
}

SERVICECATEGORIES.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

import '../model/mod_categories.dart';

class ServicesCategories {
  String collection = 'category';
  Firestore _firestore = Firestore.instance;

  Future<ModelCategories> getCategory() =>
      _firestore.collection(collection).getDocuments().then(
        (QuerySnapshot snapshot) {
          if (snapshot.documents.length == 0) {
            return null;
          }

          return ModelCategories.fromSnapshot(snapshot);
        },
      ).catchError(
        (e) => print("ERROR:::: $e"),
      );

}

我的调用堆栈

非常感谢任何改进我的代码的建议或替代解决方案。

谢谢。

>>>>>编辑

PROVIDER.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../services/serv_category.dart';
import '../model/mod_categories.dart';

class ProviderCategory with ChangeNotifier {
  ProviderCategory() {
    getCategories();
  }

  ModelCategories _categories;

  ServicesCategories _servicesCategories = ServicesCategories();

  //getter
  ModelCategories get categories => _categories;


  Future<void> getCategories() async {


    _categories = await _servicesCategories.getCategory();
    notifyListeners();

  }

  int getCategoryCount() {
    return _categories.categoryDocumentData.length;
  }
}

【问题讨论】:

    标签: flutter google-cloud-firestore provider


    【解决方案1】:

    如何在程序中使用 SERVICECATEGORIES.dart?看起来好像所有事件的集合都设置为“类别”,这导致 snapshot.documents.length 始终为 0。

    【讨论】:

    • servicecategories.dart 处理从 firebase 检索数据,然后将其传递给模型类别。但它有点奇怪......当我热刷新应用程序时,它会检索数据。这是链接share.getcloudapp.com/v1ue4WAk
    • 你能分享一下使用 servicecategories.dart 的那部分代码吗?
    • 嗨格尔格。我已经更新了上面的帖子..请参阅帖子的更新部分。谢谢。
    • 您的代码显示了一个 notifyListeners();陈述。这些监听器如何触发动作?您如何检索数据?
    猜你喜欢
    • 2021-05-15
    • 2020-09-27
    • 2019-02-22
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多