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);
});
}
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,
};
}
}
The json-structure in the database is:
database
|__news
|__post1
| |__text: "Lorem ipsum"
| |__title: "Title of post"
|
|__post2
|__ ...
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"
| .
| .
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
);
}
But this throws the exception
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)
I found in flutter and dart no code-example to load nested json with DataSnapshot. Do you know any code-sample?
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