使用Flutter从Firebase DataSnapshot获取嵌套的JSON [英] Get with Flutter a nested JSON from Firebase DataSnapshot

查看:89
本文介绍了使用Flutter从Firebase DataSnapshot获取嵌套的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将flutter与package firebase_database一起使用.加上代码

I use flutter with package firebase_database. With the code

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 .新闻课是

i get a perfect list _newsList of all queried items. The news class is

 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-结构为:

The json-structure in the database is:

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

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

Now i want to load a nested json-structure from the database with

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加载到类中的解决方案,但是我总是会遇到异常.到目前为止,我尝试过的最好的代码是

I try to find a solution to load the nested DataSnapshots into class, but i always get exceptions. The best code i tried so far is

 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):[错误:flutter/lib/ui/ui_dart_state.cc(148)]未处理的异常:类型'_InternalLinkedHashMap'不是类型'Map'的子类型E/flutter(5882):#0新News.fromSnapshot.(package: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)

E/flutter ( 5882): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map' E/flutter ( 5882): #0 new News.fromSnapshot. (package: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的代码示例.您知道任何代码示例吗?

I found in flutter and dart no code-example to load nested json with DataSnapshot. Do you know any code-sample?

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

If you want to see my full code, then look at https://github.com/matthiaw/gbh_app. The not working part is the nested json in calendar at https://github.com/matthiaw/gbh_app/blob/4de0f20f6162801db86ef6644609829c27a4dd76/lib/models/calendar.dart

推荐答案

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

I was also looking on how to handle nested json objects in Flutter with Cloud Firestore and found your post. As I solved my problem, maybe it helps you too: In the "fromJson"-factory of my model I had to parse every element in the list with jsonEncode and jsonDecode before adding it to the model.

在DatabaseService中:

in the DatabaseService:

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']);
}

这篇关于使用Flutter从Firebase DataSnapshot获取嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆