简体   繁体   中英

Flutter Riverpod : Problems fetching data from Firebase using Riverpod

I'm changing from Getx to Riverpod. So, Problems fetching data from Firebase using Riverpod.

I have two product data on the server. Initially after running, the ProductListPage doesn't show anything. 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?

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

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

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM