简体   繁体   English

Flutter Riverpod:使用 Riverpod 从 Firebase 获取数据时出现问题

[英]Flutter Riverpod : Problems fetching data from Firebase using Riverpod

I'm changing from Getx to Riverpod.我正在从 Getx 更改为 Riverpod。 So, Problems fetching data from Firebase using Riverpod.因此,使用 Riverpod 从 Firebase 获取数据时出现问题。

I have two product data on the server.我在服务器上有两个产品数据。 Initially after running, the ProductListPage doesn't show anything.最初运行后,ProductListPage 不显示任何内容。 Enter the page again and the list will be displayed.再次进入页面,将显示列表。 And every time you enter, the list is piled up.而且每次进入,名单就堆积如山。 How to fetch data from server using Riverpod?如何使用 Riverpod 从服务器获取数据?

Model Model

  class Product {
  String id;
  String name;
  String category;
  String image;
  String images;
  String desc;
  String price;
  Timestamp createdAt;
  Timestamp updatedAt;

  Product();

  Product.fromMap(Map<String, dynamic> data) {
    id = data['id'] ?? "ID Data Null";
    name = data['name'] ?? "Name Data Null";
    category = data['category'] ?? "Category Data Null";
    image = data['image'] ?? "Image Data Null";
    //images = data['images'];
    desc = data['desc'] ?? "Desc Data Null";
    price = data['price'] ?? "Price Data Null";
    createdAt = data['createdAt'];
    updatedAt = data['updatedAt'];
  }

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'category': category,
      'images': images,
      'image': image,
      'desc': desc,
      'price': price,
      'createdAt': createdAt,
      'updatedAt': updatedAt
    };
  }
}

Riverpod Provider Riverpod 提供商

 final productListProvider = StateNotifierProvider<ProductList>((ref) {
   return ProductList();
});


class ProductList extends StateNotifier<List<Product>> {
  //static Product productModel = Product();
  ProductList([List<Product> state]) : super(state ?? []);

  productAdd(Product product) {
    state.add(product);
  }

  Future<void> refreshList() async {
    getStateProducts();
  }

  getStateProducts() async {
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('Products')
        .get();
   
    snapshot.docs.forEach((document) {
   
      Product _product = Product.fromMap(document.data());
      productAdd(_product);
      print('DataBase: ${_product.name}');
    });
  }

ProductPage ListView产品页面列表查看

  class ProductListPage extends ConsumerWidget {
  

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    
    final productObj = watch(productListProvider);
    final product = watch(productListProvider.state);

    productObj.getStateProducts(); //

    return Scaffold(
      appBar: AppBar(
        title: Text('Product List'),
      ),
      body: new RefreshIndicator(
          child: ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                leading: Image.network(
                  product[index].image != null
                      ? product[index].image
                      : 'https://www.testingxperts.com/wp-content/uploads/2019/02/placeholder-img.jpg',
                  width: 120,
                  fit: BoxFit.fitWidth,
                ),
                title: Text(product[index].name),
                subtitle: Text(product[index].category),
                onTap: () {
                  // getxController.currentIndex(index);
                  // getxController.currentProduct =
                  // getxController.productList[index];
                  // return Get.to(ProductDetail(), arguments: "test");
                },
              );
            },
            itemCount: product.length,
            separatorBuilder: (BuildContext context, index) {
              return Divider(
                color: Colors.black,
              );
            },
          ),
          onRefresh: productObj.refreshList), // Refresh 
    );
  }
}
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/all.dart';

List<Product> productList = [
  Product(category: "categoryA", id: "0010", name: "ProductA"),
  Product(category: "categoryB", id: "0010", name: "ProductB"),
  Product(category: "categoryC", id: "0011", name: "ProductC"),
  Product(category: "categoryD", id: "0011", name: "ProductD"),
];

final productListStateProvider =
    StateNotifierProvider((ref) => ProductListState());

class ProductListState extends StateNotifier<AsyncValue<List<Product>>> {
  ProductListState([AsyncValue<List<Product>> state])
      : super(state ?? AsyncValue.data(<Product>[]));

  Future<List<Product>> getStateProducts() async {
    state = AsyncValue.loading();
    await Future.delayed(Duration(seconds: 2));
    final result = productList;
    state = AsyncValue.data(productList);
    return result;
  }
}

class ProductsPage extends StatefulWidget {
  @override
  _ProductsPageState createState() => _ProductsPageState();
}

class _ProductsPageState extends State<ProductsPage> {
  @override
  void initState() {
    context.read(productListStateProvider).getStateProducts();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Stackoverflow answer"),
      ),
      body: Container(
       child: RefreshIndicator(
            onRefresh: () => 
         context.read(productListStateProvider).getStateProducts(),
      child: ProductListWidget()
      ),
  ),
    );
  }
}

class ProductListWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final resultData = watch(productListStateProvider.state);
    return resultData.maybeWhen(
        data: (results) => ListView.builder(
            itemCount: results.length,
            itemBuilder: (context, index) {
              final product = results[index];
              return ListTile(
                title: Text(product.name),
                subtitle: Text(product.category),
              );
            }),
        loading: () => Center(child: CircularProgressIndicator()),
        error: (er, st) => Center(child: Text("Error occurred")), 
        orElse: () => Text("No data yet"));
  }
}

@immutable
class Product {
  final String id;
  final String name;
  final String category;
  final String image;
  final String images;
  final String desc;
  final String price;
  final dynamic createdAt;
  final dynamic updatedAt;

  Product({
    this.id,
    this.name,
    this.category,
    this.image,
    this.images,
    this.desc,
    this.price,
    this.createdAt,
    this.updatedAt,
  });
}

    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter Riverpod 和 Firebase - Flutter Riverpod and Firebase Firebase Flutter Riverpod:在使用 Riverpod 跨模型映射值时,如何从 Firebase 获取 documentID? 包含代码 - Firebase Flutter Riverpod: How do I get the documentID from Firebase when using Riverpod to map values across a model? Code Included 如何使用 Riverpod 包从 Flutter 中的 firebase 集合中获取所有文档? - How to fetch all documents from a firebase collection in Flutter using the Riverpod package? 在Flutter中使用Riverpod实现session用户数据管理 - Using Riverpod in Flutter to implement session user data management Flutter Riverpod Firebase currentUser Provider 未更新 - Flutter Riverpod Firebase currentUser Provider not updated Flutter Firestore Riverpod 获取数据问题 - Flutter Firestore Riverpod Getting Data Issue 在 Flutter StateNotifier + Riverpod 架构中初始化未来数据 - Initialize future data in a Flutter StateNotifier + Riverpod architecture Flutter Riverpod 1.0:Firebase AuthService 对象使用什么提供程序? - Flutter Riverpod 1.0: What provider to use for Firebase AuthService object? 使用 Riverpod StateNotifierProvider 更新 Flutter UI - Flutter UI update with Riverpod StateNotifierProvider 如何通过 Riverpod 的 FutureProvider 初始化 Firebase - How to initialize Firebase via Riverpod's FutureProvider
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM