Read data from GitHub hosted json file in Flutter


This is my first flutter tutorial, which explain how you can host and read json data from GitHub repository.

First up all you need to host json in GitHub Page , here is the complete guide. After that you can read the data using http package in Flutter.

First up all you need to specify the pubspec.yml settings as follows

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2

Go to your pubspec file and add the high lighted sections to use the network/web connection.

Now we need a Model class to read and hold the json object. Eventually the fetchpost Future will extract the data from GitHub.

Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}

A special function called FutureBuilder help us to feched post object.Here is the complete main.dart file

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  Future<Post> post;
  void initState() {
    super.initState();
    post = fetchPost();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: FutureBuilder<Post>(
        future: post,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return new ListView(children: <Widget>[
              new Text("Q:" + snapshot.data.question),
              new Text("A:" + snapshot.data.answer)
            ]);
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          // By default, show a loading spinner
          return CircularProgressIndicator();
        },
      )),
      floatingActionButton: FloatingActionButton(
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Post {
  final String question;
  final String answer;
  final String catagory;
  Post({this.question, this.answer, this.catagory});
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        question: json['question'],
        answer: json['answer'],
        catagory: json['catagory']);
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.