Created
August 24, 2018 18:18
-
-
Save muddassirm/df682856f88f4b10eedc91e253979f0d to your computer and use it in GitHub Desktop.
Display JSON data in Flutter : Using the setState() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:convert'; | |
import 'dart:async' show Future; | |
import 'package:flutter/services.dart' show rootBundle; | |
class Student { | |
String studentId; | |
String studentName; | |
int studentScores; | |
Student({this.studentId, this.studentName, this.studentScores}); | |
factory Student.fromJson(Map<String, dynamic> parsedJson) { | |
return Student( | |
studentId: parsedJson['id'], | |
studentName: parsedJson['name'], | |
studentScores: parsedJson['score']); | |
} | |
} | |
Future<String> _loadAStudentAsset() async { | |
return await rootBundle.loadString('assets/student.json'); | |
} | |
Future<Student> loadStudent() async { | |
await wait(5); | |
String jsonString = await _loadAStudentAsset(); | |
final jsonResponse = json.decode(jsonString); | |
return new Student.fromJson(jsonResponse); | |
} | |
Future wait(int seconds) { | |
return new Future.delayed(Duration(seconds: seconds), () => {}); | |
} | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
MyApp(); | |
@override | |
MyAppState createState() => MyAppState(); | |
} | |
class MyAppState extends State<MyApp> { | |
Student _student; | |
bool _loaded = false; | |
@override | |
void initState() { | |
super.initState(); | |
loadStudent().then((s) => setState(() { | |
_student = s; | |
_loaded = true; | |
})); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
home: new Scaffold( | |
appBar: new AppBar( | |
title: new Text('Load Json'), | |
), | |
body: _loaded | |
? new Container( | |
padding: new EdgeInsets.all(20.0), | |
child: new Row( | |
children: <Widget>[ | |
Text( | |
"Hi ${_student.studentName} your id is ${_student.studentId} and score ${_student.studentScores} ") | |
], | |
)) | |
: new Center( | |
child: new CircularProgressIndicator(), | |
)), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment