How to get data from http methods in Flutter ?

We will continue with our last section project after that I added a new file which name is api_screen.dart. This screen shows the comments from a json website to us. Let’s build with together.

Firstly, we need to add http dependencies into the pubspec.yaml file. Under the dependencies, we add http dependencies with last version at below.

After that, we need look our fetching data type from api service. So, I created a model file into the model folder which name is Comment.dart. We have 4 entities there for mapping object from to json object.

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class Comment {
  final int postId;
  final int id;
  final String name;
  final String email;
  final String body;

  Comment(
      {@required this.postId,
      @required this.id,
      @required this.name,
      @required this.email,
      @required this.body});

  factory Comment.fromJson(Map<String, dynamic> json) {
    return Comment(
        postId: json['postId'] as int,
        id: json['id'] as int,
        name: json['name'] as String,
        email: json['email'] as String,
        body: json['body'] as String);
  }
}

So, I need a service file for fetching data from service. Then, I create a file which name is ApiService.dart. In this class, I define api service url and getComments() method. This method returns the list of comment data object if status code is 200.

import 'dart:convert';
import 'package:flutter_splash/models/Comment.dart';
import 'package:http/http.dart';

class ApiService {
  final String apiServiceUrl = "https://jsonplaceholder.typicode.com/comments";

  Future<List<Comment>> getComments() async {
    Response res = await get(apiServiceUrl);

    if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);

      List<Comment> comments = body
          .map(
            (dynamic item) => Comment.fromJson(item),
          )
          .toList();
      return comments;
    } else {
      throw "Opps.. A problem !";
    }
  }
}

Now, I need a screen for showing data from api service. Into the screens, I created a screen which name is api_screen.dart. There is a listView for showing the all comments title.

import 'package:flutter/material.dart';
import 'package:flutter_splash/models/Comment.dart';
import 'package:flutter_splash/services/api/api.dart';

class ApiScreen extends StatelessWidget {
  final ApiService apiService = ApiService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Comments"),
      ),
      body: FutureBuilder(
          future: apiService.getComments(),
          builder:
              (BuildContext context, AsyncSnapshot<List<Comment>> snapshot) {
            if (snapshot.hasData) {
              List<Comment> comments = snapshot.data;
              return ListView(
                  children: comments
                      .map(
                        (Comment comment) => ListTile(
                            title: Text(comment.email),
                            subtitle: Text(comment.body)),
                      )
                      .toList());
            } else {
              return Center(child: CircularProgressIndicator());
            }
          }),
    );
  }
}

We implement all necessary units for running. There are 2 ways for testing on emulator device. One of them, in VS Code, debug mode with F5. Another way with a command on terminal,

  • flutter run

If we run the application with flutter run, we need to press ‘r’ on terminal for seeing the changes on app when we develop something.

main_screen.dart

For sample code on github : isoguzay

Thanks for reading this article ! Happy coding days..

I used some reference websites, thank you.. Check for more information: