MappedListIterable不是子类型

时间:2019-08-13 23:21:30

标签: flutter dart google-cloud-firestore

我不熟悉dart和dart,并尝试从流存储中以流形式获取数据并提供给ListView,但我一直遇到此错误:

type 'MappedListIterable<DocumentSnapshot, Product>' is not a subtype
of type 'List<Product>'

我在stackoverflow上也看到过其他几篇文章,但它们要么无济于事,要么不适用于我的情况。

这是我的产品页面小部件:

import 'package:xxx/models/Product.dart';
import 'package:agrogator/screens/products/widgets/products_list.dart';
import 'package:xxx/services/product.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsScreen extends StatelessWidget {
  ProductsScreen({Key key}) : super(key: key);

  final product = ProductService();

  // This widget is the productsucts page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  @override
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return StreamProvider<List<Product>>.value(
      value: product.streamProducts(),
      child: new Scaffold(
        appBar: new AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: new Text("xxx"),
        ),
        body: new ProductsList(),
        floatingActionButton: new FloatingActionButton(
          onPressed: () {},
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}

这是我的ProductsList小部件:

import 'package:xxx/models/Product.dart';
import 'package:xxx/screens/products/widgets/product_item.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProductsList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var products = Provider.of<List<Product>>(context);

    return Container(
      height: 100,
      child: ListView(
        children: products.map((product) {
          return new ProductItem(product: product);
        }).toList(),
      ),
    );
  }
}

这是我的ProductItem小部件:

import 'package:xxx/models/Product.dart';
import 'package:flutter/material.dart';

class ProductItem extends StatelessWidget {
  final Product product;

  ProductItem({this.product});

  @override
  Widget build(BuildContext context) {
    return Text(product.name, style: TextStyle(color: Colors.black));
  }
}

这是我的产品型号:

import 'package:cloud_firestore/cloud_firestore.dart';

class Product {
  String uid;
  String name;
  String unit;
  int avgQuantity;
  double avgWeight;
  double previousAvgPrice;
  double currentAvgPrice;
  String lastUpdatedBy;
  String lastUpdatedAt;
  String remarks;

  Product(
      {this.uid,
      this.name,
      this.unit,
      this.avgQuantity,
      this.avgWeight,
      this.previousAvgPrice,
      this.currentAvgPrice,
      this.lastUpdatedBy,
      this.lastUpdatedAt,
      this.remarks});

  factory Product.fromFirestore(DocumentSnapshot doc) {
    Map data = doc.data;

    return Product(
        uid: doc.documentID,
        name: data["name"],
        unit: data["unit"],
        avgQuantity: data["avgQuantity"],
        avgWeight: data["avgWeight"],
        previousAvgPrice: data["previousAvgPrice"],
        currentAvgPrice: data["ccurrentAvgPrice"],
        lastUpdatedBy: data["lastUpdatedBy"],
        lastUpdatedAt: data["lastUpdatedAt"],
        remarks: data["remarks"]);
  }
}

我的服务:

import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
  final Firestore _db = Firestore.instance;

  Stream<List<Product>> streamProducts() {
    var ref = _db.collection("products");

    return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc)));
  }
}

2 个答案:

答案 0 :(得分:11)

在您的服务中添加.toList()

像下面这样

import 'package:xxx/models/Product.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductService {
    final Firestore _db = Firestore.instance;

    Stream<List<Product>> streamProducts() {
        var ref = _db.collection("products");

        return ref
        .snapshots()
        .map((list) => list.documents.map((doc) => Product.fromFirestore(doc))).toList(); // <= here
   }
}

答案 1 :(得分:0)

您可以尝试一下。希望这会有所帮助

产品型号

class Product {
    String uid;
    String name;
    String unit;
    int avgQuantity;
    double avgWeight;
    double previousAvgPrice;
    double currentAvgPrice;
    String lastUpdatedBy;
    String lastUpdatedAt;
    String remarks;

    Product({this.uid,
    this.name,
    this.unit,
    this.avgQuantity,
    this.avgWeight,
    this.previousAvgPrice,
    this.currentAvgPrice,
    this.lastUpdatedBy,
    this.lastUpdatedAt,
    this.remarks});
}

产品服务

class ProductService {
  Stream<List<Product>> streamProducts() {
    return _FirestoreStream<List<Product>>(
      apiPath: "products",
      parser: FirestoreProductsParser(),
    ).stream;
  }
}

abstract class FirestoreNodeParser<T> {
  T parse(QuerySnapshot querySnapshot);
}

class FirestoreProductsParser extends FirestoreNodeParser<List<Product>> {
  List<Product> parse(QuerySnapshot querySnapshot) {
    var products = querySnapshot.documents.map((documentSnapshot) {
      return Product(
        uid: doc.documentID,
        name: data["name"],
        unit: data["unit"],
        avgQuantity: data["avgQuantity"],
        avgWeight: data["avgWeight"],
        previousAvgPrice: data["previousAvgPrice"],
        currentAvgPrice: data["ccurrentAvgPrice"],
        lastUpdatedBy: data["lastUpdatedBy"],
        lastUpdatedAt: data["lastUpdatedAt"],
        remarks: data["remarks"]
      );
    }).toList();
    products.sort((lhs, rhs) => rhs.uid.compareTo(lhs.uid));
    return products;
  }
}

class _FirestoreStream<T> {
  _FirestoreStream({String apiPath, FirestoreNodeParser<T> parser}) {
    CollectionReference collectionReference = Firestore.instance.collection(apiPath);
    Stream<QuerySnapshot> snapshots = collectionReference.snapshots();
    stream = snapshots.map((snapshot) => parser.parse(snapshot));
  }

  Stream<T> stream;
}