Task Flutter Get AdoptApp Button
Pets Adoption App ?
Instructions
- Fork and clone this repository to your
Development
folder. - Endpoints:
Get pets, type: Get, https://coded-pets-api-crud.herokuapp.com/pets
Create a new pet, type: Post, https://coded-pets-api-crud.herokuapp.com/pets
Update a pet, type: Put, https://coded-pets-api-crud.herokuapp.com/pets/{petId}
Delete a pet, type: Delete, https://coded-pets-api-crud.herokuapp.com/pets/{petId}
Adopt a pet, type: Post, https://coded-pets-api-crud.herokuapp.com/pets/adopt/{petId}
Part 1: Get Data
- Install
dio
into your project:
flutter pub add dio
- Create a folder named
services
, inside it create a file calledpets_services.dart
. - Import
dio
package inpets_services.dart
.
import "package:dio/dio.dart";
- Create a new
DioClient
class and initialize a new dio instance. - Create a function to get the list of pets and name it
getPets
. - Our endpoint is:
Get, https://coded-pets-api-crud.herokuapp.com/pets
- Dont forget to ass async and await
- Store the response of the request in a
Response
object. - In your
PetsProvider
, create a new function that callsgetPets
. - Make the button in the home_page call the provider function.
- Print the response in the debug console.
Part 2: Use the data
- Add the following packages
flutter pub add json_serializable , build_runner
- Go to the pets model and add this code before the class
import 'package:json_annotation/json_annotation.dart';
part 'pet.g.dart';
@JsonSerializable()
- Run this in terminal
flutter pub run build_runner build
- Add the following code in the pet model
factory Pet.fromJson(Map<String, dynamic> json) => _$PetFromJson(json);
Map<String, dynamic> toJson() => _$PetToJson(this);
- In
pets_services.dart
save the response in a list of pets and convert from Json to petList<Pet> pets =(res.data as List).map((pet) => Pet.fromJson(pet)).toList();
- Add try and catch in case of Dio Error try{…}on DioError catch(error){…}
- Change return type to List, fix the function so that it returns a future list of pets
- Finally fix the provider as well by adding async and await