Calling Api in Flutter.
Hello! Today we will see how to call an API in Flutter.
We will use a structure to call an API. We'll mostly use the API in the Screen folder.
We use the following folders and file names:
model=> resModal.dart (Each API response is dependent on a file, and each API has its own.)
screen=>home.dart (the screen where we want to invoke the API and display the result)
services=>api_calls.dart (created and attained by oneself).
services=> user_api.dart (This file will contain a class with a function that can be called.)
Required Dependencies: http: any
As an example, consider the following API call: user_api.dart, shown below:
import 'api_calls.dart'; import 'package:flutter/material.dart'; import '../model/responseModal.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; class UserApi{ const baseUrl = "http://webgrid.in/projects/projectname/"; static Future<responseModal?> api_call_fun() async { try { final res = await post({},"${baseUrl}api_name" , {}); if (res != null) { return responseModal.fromJson(jsonDecode(res.body)); } else { print("Null Response"); return null; } } catch (e) { debugPrint('hello bev=bug $e '); return null; } } }
How to use the user_api function in the screen.
import '../model/
responseModal.dart';
Import above in top of imports in the class of screen.
Should write the following process, which extends State.
List<favlist> reslist=[]; void initState(){ super.initState(); call_api(); } Future<void> call_api() async{ await UserApi.api_call_fun().then((data) => { if(data != null){ setState(() { if(data.error=="0"){ reslist=data.list!; } else{ toast("Welcome To Wallet"); } }) } }); }
After calling this function, the data from the API will be stored in the appropriate list or object.
Thank you.