从Firestore提取数据并将其映射到提供程序对象

时间:2019-08-04 13:02:08

标签: flutter google-cloud-firestore provider

在Flutter中将Firestore与提供程序(状态管理)结合使用时遇到问题。 我的问题主要是在类上映射从Firestore检索到的数据。 ->将Firebase数据反序列化为Dart类

我能够从Firestore检索数据并将其打印到控制台中。

如果我想使用json.decode,我总是会得到“ xx型不是'Map'类型的子类型”,这里也提到了https://github.com/flutter/flutter/issues/17417

我的跑步课

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

enum Complexity { simple, challenging, hard }

class Run with ChangeNotifier {
  final String id;
  final String title;
  final List<String> workouts;
  final String imageUrl;
  final List<String> intervals;
  final List<String> steps;
  final int duration;
  Complexity complexity;
  final bool isRecovery;
  bool isBeginner;

  Run(
      {@required this.id,
      @required this.title,
      @required this.workouts,
      @required this.imageUrl,
      @required this.intervals,
      @required this.steps,
      this.duration,
      this.complexity,
      this.isRecovery,
      this.isBeginner});

  factory Run.fromDocument(DocumentSnapshot doc) {
    return Run(
        id: doc.documentID,
        title: doc['title'] ?? '',
        workouts: doc['workouts'] ?? 0,
        imageUrl: doc['imageUrl'] ?? '',
        intervals: doc['intervals'] ?? 0,
        steps: doc['steps'] ?? 0);
  }

我的Runs类应该获取数据

import 'package:flutter/material.dart';
import 'package:xxx/providers/run.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:convert';

final runsRef = Firestore.instance.collection('runs');

class Runs with ChangeNotifier {
  List<Run> _items = [];

  fetchRuns() async {
    DocumentSnapshot snapshot =
        await runsRef.getDocuments().then((QuerySnapshot snapshot) {
      snapshot.documents.forEach((DocumentSnapshot doc) {
        print(doc.data);
      });
    });
  }
  1. 我想调用fetchRuns函数以获取集合中的所有文档
  2. 我想将此检索到的数据映射到我的班级
  3. 我想使用此类作为提供者以向不同的屏幕提供状态/数据

我陷入了第2步,无法真正解决问题。

1 个答案:

答案 0 :(得分:0)

我正在使用流,这就是我映射结果的方式。

  Stream<List<Run>> fetchRuns() {
    var snaps = Firestore.instance.collection('runs').snapshots();
    return snaps.map( (list) => {
          return list.documents.map((doc) => Run.fromDocument(doc)).toList()
       }
     );
  }

https://github.com/aaronksaunders/flutter_firebase_auth_app

请参见lib/services/data.dart