-
Notifications
You must be signed in to change notification settings - Fork 10
/
Example2.dart
61 lines (53 loc) · 1.73 KB
/
Example2.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import 'dart:async';
import 'package:advanced_flutter_example/DefaultAppBar.dart';
import 'package:advanced_flutter_example/examples/readingJsonFile/Planet.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
class Example2 extends StatefulWidget {
Example2();
final String title = "Reading Json files";
final String exampleUrl =
"https://github.com/Ephenodrom/FlutterAdvancedExamples/tree/master/lib/examples/readingJsonFile";
@override
_Example2State createState() => _Example2State();
}
class _Example2State extends State<Example2> {
List<Planet> planets = [];
@override
void initState() {
super.initState();
loadPlanetsFromAsset().then((planets) {
setState(() {
this.planets.addAll(planets);
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: DefaultAppBar(widget.title, widget.exampleUrl),
body: ListView.builder(
itemCount: planets.length,
itemBuilder: (BuildContext context, index) {
return ListTile(
title: Text(planets.elementAt(index).name),
subtitle: Text("Distance from sun : " +
planets.elementAt(index).distance +
" km"),
);
}));
}
Future<List<Planet>> loadPlanetsFromAsset() async {
String content =
await rootBundle.loadString("assets/json/solarsystem.json");
Map<String, dynamic> contentAsMap = json.decode(content);
List data = contentAsMap["data"];
List<Planet> list = [];
data.forEach((e) {
Planet planet = new Planet.fromJson(e);
list.add(planet);
});
return list;
}
}