Press "Enter" to skip to content

Flutter: Fetch Data to List from JSON API

On previous article we learnt how to get and fetch json data from a server hosted api. Here we discuss how to list those data on screen using a list view builder.

On ‘lib’ folder we created a folder to keep model class. On this folder created dart file named ‘members.dart’ (give any name that you wish).

On this file, specify the values according to your json data:

class Members {
  String memberId;
  String name;
  String phone;

  Members(this.memberId, this.name);
  Members.fromJson(Map<String, dynamic>json){
    memberId = json['member_id'];
    phone = json['phone'];
    name = json['name'];
  }
}

On your main file, import model dart file(members).

import 'package:api_app/models/members.dart';
Flutter Fetch Data to List View from JSON API

On initState, Call function fetchData()

 @override
 void initState() {
   fetchData().then((value){
       _members.addAll(value);
     });
   }

fetchData:

Future<List<Members>> fetchData() async{
    var members = List<Members>();
    var url ='http://karad.sxxx.com/get-all-members';
    var response = await http.get(url);
    var jsonMembers = json.decode(response.body);
    setState(() {
      members =  jsonMembers.map<Members>((json) => new Members.fromJson(json)).toList();
    });
    return members;
  }

On the build section, you can list the data using ListView.Builder.

ListView.builder(
                    itemBuilder: (context,index){
                      return Card(
                        child: Container(
                          //height: 1
                          padding: EdgeInsets.all(15),
                          child:  Column(
                            children: <Widget>[
                              Text(_members[index].name),
                            ],
                          ),
                        ),
                      );

                     },
                      itemCount: _members.length,
                    ),

Full code (main.dart)

import 'package:api_app/models/members.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Members> _members = List<Members>();

 @override
 void initState() {

   fetchData().then((value){
       _members.addAll(value);
     });
   }

  Future<List<Members>> fetchData() async{
    var members = List<Members>();
    var url ='http://karad.sxxx.com/get-all-members';
    var response = await http.get(url);
    var jsonMembers = json.decode(response.body);
    setState(() {
      members =  jsonMembers.map<Members>((json) => new Members.fromJson(json)).toList();
    });
    return members;
  }

  @override
  Widget build(BuildContext context) {
    print(_members.length);
    return Scaffold(
      appBar: AppBar(
        title: Text('Fetch Data from Json API'),
      ),
      body:   ListView.builder(
                    itemBuilder: (context,index){
                      return Card(
                        child: Container(
                          //height: 1
                          padding: EdgeInsets.all(15),
                          child:  Column(
                            children: <Widget>[
                              Text(_members[index].name),
                            ],
                          ),
                        ),
                      );

                     },
                      itemCount: _members.length,
                    ),

    );
  }
}

Sample Output:

Flutter Fetch Data to List View Builder from JSON API

Be First to Comment

Leave a Reply