Skip to content

Instantly share code, notes, and snippets.

@muddassirm
Last active April 26, 2021 18:04
Show Gist options
  • Save muddassirm/7e37653904977a379aabb4f47a7ff85a to your computer and use it in GitHub Desktop.
Save muddassirm/7e37653904977a379aabb4f47a7ff85a to your computer and use it in GitHub Desktop.
Display JSON data in Flutter : Using the main() function
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 {
String jsonString = await _loadAStudentAsset();
final jsonResponse = json.decode(jsonString);
return new Student.fromJson(jsonResponse);
}
void main() async {
Student student = await loadStudent();
runApp(MyApp(student: student));
}
class MyApp extends StatefulWidget {
final Student student;
MyApp({this.student});
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Load Json'),
),
body: new Container(
padding: new EdgeInsets.all(20.0),
child: new Row(
children: <Widget>[
Text(
"Hi ${widget.student.studentName} your id is ${widget.student.studentId} and score ${widget.student.studentScores} ")
],
))),
);
}
}
@HAFDIAHMED
Copy link

where is the json file ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment