Flutter Tutorial: http request and rest api



In this tutorial, I will show you how to make an HTTP request with a REST API using flutter and how you can display the data into a ListView so let's begin.

for this tutorial, we will not use a large Restful API, but we will use JSONPlaceholder, a fake API for testing and prototyping.

this is the link of JSONPlaceholder: https://jsonplaceholder.typicode.com/

now lets' start coding our app.

Create a new Project

first of all, create a new flutter project. and let's start by importing some library

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';


right after the material package, add these lines. it's possible that you can face a problem while adding the http package so to fix that open your pubspec.yaml file and add the Http dependence

 
   http: ^0.12.0


okay now that we have added our libraries, let's create the function that will fetch the data from the API

inside the State Class add a this function

 List data; //Declare a data variable of type List

//This function will alow us to connect to the server and fetch the data
  Future<StringgetData() async{
    http.Response response = await http.get(
        Uri.encodeFull("https://jsonplaceholder.typicode.com/posts/"),
      headers:{
           //this line will only allow us to get json data
          "Accept""application/json"
      }
    );
    
    //this part will refrech the layout for us and    
    setState(() {
      //this line will convert a json string into a list
      data = json.decode(response.body);
    });

  }


Now that we have created the function that will fetch the data for us, we need now to call this function before the app render the layout, for this, we will use initState function

  //this function allow us to fetch date before rendering the layout
  //if there is a network problem of course it will take some time
  @override
  void initState() {
    // TODO: implement initState
    this.getData();
  }



Okay now we have done 80% of the project, now we need to implement the layout and display the result.

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Rest Api"),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: (data == null) ? 0 : 30,
                itemBuilder: (BuildContext context, int index){
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(18.0),
                      child: Text(data[index]["title"]),
                    ),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }

and that's it, you can run the app and see the result, of course, you can use any other API that you want, but make sure to read the whole documentation because it may be different of this example.

this is the whole code of the app

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
void main() => runApp(MaterialApp(
  
  home: HttpApp(),
));

class HttpApp extends StatefulWidget {
  @override
  _HttpAppState createState() => _HttpAppState();
}

class _HttpAppState extends State<HttpApp> {
  List data;
  static String API_KEY = "DEMO_KEY";
  String Url = "https://api.nasa.gov/insight_weather/?api_key=${API_KEY}&feedtype=json&ver=1.0";

  //This function will alow us to connect to the server and fetch the data
  Future<StringgetData() async{
    http.Response response = await http.get(
        Uri.encodeFull("https://jsonplaceholder.typicode.com/posts/"),
      headers:{
           //this line will only allow us to get json data
          "Accept""application/json"
      }
    );
    
    //this part will refrech the layout for us and    
    setState(() {
      //this line will convert a json string into a list
      List data = json.decode(response.body);
    });

  }
  //this function allow us to fetch date before rendering the layout
  //if there is a network problem of course it will take some time
  @override
  void initState() {
    // TODO: implement initState
    this.getData();
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Rest Api"),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemCount: (data == null) ? 0 : 30,
                itemBuilder: (BuildContext context, int index){
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(18.0),
                      child: Text(data[index]["title"]),
                    ),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

if you had any problem while coding the app you can put the problem in a comment and we will help you.

Flutter Tutorial: http request and rest api Flutter Tutorial: http request and rest api Reviewed by Medics on July 21, 2020 Rating: 5

6 comments:

  1. hi, it doesn't work for me? i paste the final code in a new project but i got errors.
    can you please help me with this?
    thank you!

    ------------------------------------------------------------
    Launching lib\main.dart on SM G960U1 in debug mode...
    Running Gradle task 'assembleDebug'...

    Compiler message:
    Error: Could not resolve the package 'http' in 'package:http/http.dart'.
    lib/main.dart:5:8: Error: Not found: 'package:http/http.dart'
    import 'package:http/http.dart' as http;
    ^
    lib/main.dart:24:10: Error: 'Response' isn't a type.
    http.Response response = await http.get(
    ^^^^^^^^
    lib/main.dart:24:36: Error: Method not found: 'get'.
    http.Response response = await http.get(
    ^^^
    Invalid depfile: C:\src\Projects\flutter_app_http_rest_api\flutter_app_http_rest_api\.dart_tool\flutter_build\19ccd2f69f4e7207a854c45bd5b85781\kernel_snapshot.d
    Invalid depfile: C:\src\Projects\flutter_app_http_rest_api\flutter_app_http_rest_api\.dart_tool\flutter_build\19ccd2f69f4e7207a854c45bd5b85781\kernel_snapshot.d

    Compiler message:
    Error: Could not resolve the package 'http' in 'package:http/http.dart'.
    lib/main.dart:5:8: Error: Not found: 'package:http/http.dart'
    import 'package:http/http.dart' as http;
    ^
    lib/main.dart:24:10: Error: 'Response' isn't a type.
    http.Response response = await http.get(
    ^^^^^^^^
    lib/main.dart:24:36: Error: Method not found: 'get'.
    http.Response response = await http.get(
    ^^^
    Unhandled exception:
    FileSystemException(uri=org-dartlang-untranslatable-uri
    :package%3Ahttp%2Fhttp.dart; message=StandardFileSystem only supports file:* and data:* URIs)
    #0 StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
    #1 asFileUri (package:vm/kernel_front_end.dart:613:37)
    #2 writeDepfile (package:vm/kernel_front_end.dart:807:21)
    <
    asynchronous suspension>
    #3 FrontendCompiler.compile (package:frontend_server/frontend_server.dart:555:15)

    #4 _FlutterFrontendCompiler.compile (package:flutter_frontend_server/server.dart:40:22)
    #5 starter (package:flutter_fro
    ntend_server/server.dart:178:27)
    #6 main (file:///C:/b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30)
    #7 _startIsolate. (dart:isolate-patch/isolate_patch.dart:299:32)
    #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

    Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
    build failed.

    FAILURE: Build failed with an exception.

    * Where:
    Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 896

    * What went wrong:
    Execution failed for task ':app:compileFlutterBuildDebug'.
    > Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    * Get more help at https://help.gradle.org

    BUILD FAILED in 8s
    Exception: Gradle task assembleDebug failed with exit code 1





    ReplyDelete
    Replies
    1. hi, this is me again.
      I fixed the problem.

      thanks anyway

      Delete
    2. did you add the http package

      Delete
  2. I run the program, no errors, but the application only displays the title bar. it does suppose to to something else right?

    thanks

    ReplyDelete
    Replies
    1. have you checked your internet, becuase the project need internet connection to run, check the emulator network

      Delete
  3. Hello, I run but it only shows the title bar. My internet connection is normal, my emulator is my cell phone.

    ReplyDelete

-->
Powered by Blogger.