Introduction

In this article, What we are gonna learn is about how we can fetch API in the flutter app using Riverpod instead of the Future.

**Riverpod; “**Also a provider but a different one”

What you do here is Create a Provider and Consumer the Provider. But today we are just gonna see how to make API calls.

Getting Started

Prerequisites:

  • Flutter
  • flutter_riverpod: any
  • HTTP: any
  • Fake API (JSON placeholder)

Create a new flutter project:

flutter create my_project_name

Install the package:

Go to the pubspec file and add the dependencies’.

dependencies:
  flutter:
   sdk: flutter
  cupertino_icons: ^1.0.0
  flutter_riverpod: ^0.12.1
  http: ^0.12.2

Create the Dart model class:

Go to JSON place holder/photos and copy the JSON raw and paste JSON to dart and give your class name to generate the model class.

[
    {
        "albumId": 1,
        "id": 1,
        "title": "accusamus beatae ad facilis cum similique qui sunt",
        "url": "https://via.placeholder.com/600/92c952",
        "thumbnailUrl": "https://via.placeholder.com/150/92c952"
    }
]

Now create a model.dart file copy the generated code and place it under lib/model/model.dart

class PhotoModel {
  int albumId;
  int id;
  String title;
  String url;
  String thumbnailUrl;

  PhotoModel({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  PhotoModel.fromJson(Map<String, dynamic> json) {
    albumId = json['albumId'];
    id = json['id'];
    title = json['title'];
    url = json['url'];
    thumbnailUrl = json['thumbnailUrl'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['albumId'] = this.albumId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['url'] = this.url;
    data['thumbnailUrl'] = this.thumbnailUrl;
    return data;
  }
}

This how your model class will look.

#flutter #api #mobile-apps #programming #developer

Fetching API Using Riverpod In Flutter
44.45 GEEK