【问题标题】:Get with Flutter a nested JSON from Firebase DataSnapshot使用 Flutter 从 Firebase DataSnapshot 获取嵌套的 JSON
【发布时间】:2019-07-28 16:42:37
【问题描述】:

我将颤振与包 firebase_database 一起使用。用代码

final FirebaseDatabase _database = FirebaseDatabase.instance;

@override
void initState() {
  super.initState();
  _newsList = new List();

  _newsQuery = _database
     .reference()
     .child('news')
     .orderByChild('published')
     .limitToFirst(10);

  _newsQuery.onChildAdded.listen(_onEntryAdded);
}

_onEntryAdded(Event event) {
  setState(() {
    News n = News.fromSnapshot(event.snapshot);
    _newsList.add(n);
  });
}

我得到了所有查询项目的完美列表_newsList。新闻类是

 import 'package:firebase_database/firebase_database.dart';

 class News {
   String key;
   String image;
   String text;
   String title;
   String published;

   News(this.image, this.text, this.published);

   News.fromSnapshot(DataSnapshot snapshot) :
     key = snapshot.key,
     text = snapshot.value["text"],
     title = snapshot.value["title"],
     image = snapshot.value["image"],
     published = snapshot.value["published"];

   toJson() {
     return {
     "image": image,
     "text": text,
     "title": title,
     "published": published,
   };
  }
}

数据库中的json结构为:

database
|__news
    |__post1
    |    |__text: "Lorem ipsum"
    |    |__title: "Title of post"
    |
    |__post2
         |__ ...

现在我想从数据库中加载一个嵌套的 json 结构

database
|__news
    |__category1
    |    |
    |    |__post1
    |    |    |__text: "Lorem ipsum 1"
    |    |    |__title: "Title of post1"
    |    |__post2
    |    |    |__text: "Lorem ipsum 2"
    |    |    |__title: "Title of post2"
    |    |__description: "description text"
    |    |__id: "id of category"
    |    .
    |    .
    |
    |__category2
    |    |
    |    |__post34
    |    |    |__text: "Lorem ipsum 34"
    |    |    |__title: "Title of post34"
    |    .
    |    .

我试图找到一个解决方案来将嵌套的 DataSnapshots 加载到类中,但我总是遇到异常。到目前为止我尝试过的最好的代码是

 class News {
   final List<Category> categories;

   News({this.categories});

   factory News.fromSnapshot(DataSnapshot snapshot) {

   List<dynamic> listS = snapshot.value;

   listS.forEach((value) =>
     print('V $value')
   );

   List<Category> list = listS.map((i) => Category.fromJson(i)).toList();

   return News(
     categories: list
   );

 }

但这会引发异常

E/flutter (5882): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:类型“_InternalLinkedHashMap”不是“Map”类型的子类型 E/颤振(5882):#0 新 News.fromSnapshot。 (包:app/models/news.dart:23:55) E/flutter (5882):#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29) E/flutter (5882): #2 ListIterable.toList (dart:_internal/iterable.dart:219:19)

我在 Flutter 和 dart 中发现没有使用 DataSnapshot 加载嵌套 json 的代码示例。你知道任何代码示例吗?

如果您想查看我的完整代码,请查看https://github.com/matthiaw/gbh_app。不工作的部分是 https://github.com/matthiaw/gbh_app/blob/4de0f20f6162801db86ef6644609829c27a4dd76/lib/models/calendar.dart 的日历中的嵌套 json

【问题讨论】:

  • 请为两个查询结果添加一个示例 JSON 返回数据。

标签: json firebase-realtime-database dart flutter


【解决方案1】:

我还在研究如何使用 Cloud Firestore 在 Flutter 中处理嵌套的 json 对象,并找到了您的帖子。当我解决了我的问题时,也许它对你也有帮助:在我的模型的“fromJson”工厂中,我必须先用 jsonEncode 和 jsonDecode 解析列表中的每个元素,然后再将其添加到模型中。

在数据库服务中:

Future<LocationRecordings> getLocationRecordings(String location) async {
 DocumentReference document = locationRecordingsCollection.document((location));

 DocumentSnapshot documentSnapshot =  await document.get();
 var data = LocationRecordings.fromJson(documentSnapshot.data);
 return data;
}

在模型中:

factory LocationRecordings.fromJson(Map<String, dynamic> json) {
 List<Recording> recList = [];

 List<dynamic>.from(json['recordings']).forEach((content) {
      Recording recording = Recording.fromJson(jsonDecode(jsonEncode(content)));
      recList.add(recording);
   });
 return new LocationRecordings(recordings: recList, state: json['state']);
}

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-01-19
    • 2023-03-20
    • 2016-08-22
    • 2015-10-03
    • 2019-07-08
    相关资源
    最近更新 更多