【问题标题】:Flutter: Items from Firestore Not Shown in the GridView until RefreshFlutter:来自 Firestore 的项目在刷新之前未显示在 GridView 中
【发布时间】:2020-11-08 22:50:26
【问题描述】:

我在这里有一个连接到 Firestore 后端的颤振应用程序,我在这里遇到了一个奇怪的行为。

当应用程序启动或我进行热重启时,从数据库中获取的项目会显示一秒钟然后再次消失,我必须应用 RefreshIndicator 并向下拖动屏幕以刷新产品并让它们再次出现。

这是我获取项目的代码:

Future<void> fetchitems() async {
  try {
    final List<Product> loadedProducts = [];

    final response = await Firestore
      .instance
      .collection("products")
      .getDocuments();

    response.documents.forEach((element) {
      loadedProducts.add(Product(
        id: element.documentID,
        title: element.data['title'],
        description: element.data['description'],
        price: element.data['price'],
        imageUrl: element.data['imageUrl']
      ));
    });

    _items = loadedProducts;
    notifyListeners();
  } catch (error) {
    print(error);
  }
}

这是 GridView 及其接收项目的方式:

Widget build(BuildContext context) {
    final productsData = Provider.of<Products>(context);
    final products = productsData.items;
    return GridView.builder(
        padding: const EdgeInsets.all(10.0),
          itemCount: products.length,
          itemBuilder: (ctx, i) => ChangeNotifierProvider.value(

            value: products[i],
            child: ProductItem(),
          ),

这里是我调用 GridView 的地方:

class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> {
  var _isIntit = true;
  var _isLoading = false;

  Future<void> _refreshProducts(BuildContext context) async {
    await Provider.of<Products>(context).fetchAndSetProducts();
  }

  @override
  void initState() {
    super.initState();
  }
  @override
  void didChangeDependencies() {
    if (_isIntit) {
      setState(() {
        _isLoading = true;
      });

      Provider.of<Products>(context).fetchitems().then((_) {
        setState(() {
          _isLoading = false;
        });

      });

    }
    _isIntit = false;
    super.didChangeDependencies();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: _isLoading ? Center(child: CircularProgressIndicator(), ) : RefreshIndicator(
        onRefresh: () => _refreshProducts(context),
        child: ProductsGrid()),
    );
  }
}

【问题讨论】:

  • 这段代码不是问题,你可以展示你如何在gridview中使用_items
  • 我添加了 GridView 的代码以及它如何接收项目

标签: firebase flutter gridview google-cloud-firestore


【解决方案1】:
final productsData = Provider.of<Products>(context, listen: false);

listen: false 确保构建不会在同一个构建中再次触发。

【讨论】:

  • 我试过了,设置了listen: false,但还是遇到同样的问题
  • 从你调用这个小部件的地方,给我看那个代码。
  • 我添加了我称之为 ProductsGrid 的地方
  • 尝试去掉RefreshIndicator,直接添加ProductsGrid(),看看是否有效?然后我们可以找到其他一些问题。
  • _isLoading 是问题所在,它没有返回正确的布尔值,添加打印语句或调试,看看有什么问题
猜你喜欢
  • 2018-11-22
  • 2022-12-09
  • 2021-12-03
  • 2021-11-30
  • 2019-08-21
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多