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']);
  }
}

How to create json data server with GitHub Pages


json files were widely used for hold data for apps and web services. Reading and writing speed of json will be faster than expected, in effect app using json will fetch data from web in a quick way.

So where should I put the json on the web ?, Google drive formerly support the accessing of json file directly, soon they removed this feature. Or you can host those files on your own server

With GitHub pages can host json file which can accessed by any app. The url would form like

<username>.githubio/<json-file>

You can create one GitHub page per user and unlimited on Organization. In either case you repository name should match the <organisation name> / <username>.github.io. You can add folders and files inside the repository

for more guide how to create GitHub Pages go to the official GitHubPage Site