API CALL IN FLUTTER - Flutter provides http package to use http(online) resources
API stands for application programming interface, which are a set of definitions and protocols(rules) for building & integrating application.
How does it works?
APIs let your product or service communicate with other products and services without having to know how they’re implemented. This can simplify app development, saving time and money. When you’re designing new tools and products—or managing existing ones—APIs give you flexibility; simplify design, administration, and use; and provide opportunities for innovation.
APIs are sometimes thought of as contracts, with documentation that represents an agreement between parties: If party 1 sends a remote request structured a particular way, this is how party 2’s software will respond.
Because APIs simplify how developers integrate new application components into an existing architecture, they help business and IT teams collaborate. Business needs often change quickly in response to ever shifting digital markets, where new competitors can change a whole industry with a new app. In order to stay competitive, it's important to support the rapid development and deployment of innovative services. Cloud-native application development is an identifiable way to increase development speed, and it relies on connecting a microservices application architecture through APIs.
APIs are a simplified way to connect your own infrastructure through cloud-native app development, but they also allow you to share your data with customers and other external users. Public APIs represent unique business value because they can simplify and expand how you connect with your partners, as well as potentially monetize your data (the Google Maps API is a popular example).
APIs let you open up access to your resources while maintaining security and control. How you open access and to whom is up to you. API security is all about good API management, which includes the use of an API gateway. Connecting to APIs, and creating applications that consume the data or functionality exposed by APIs, can be done with a distributed integration platform that connects everything—including legacy systems, and the Internet of Things (IoT).
API call in flutter
The http package uses await and async features and it enables many high-level methods such as read, get, post, put, head, and delete methods for sending and receiving data from remote locations. These methods simplify the development of REST-based mobile applications. The detail explanation of the core methods of the http package are as follows: Read: This method is used to read or retrieve the representation of resources. It requests the specified url by using the get method and returns the response as Future .
home_page.dart
import 'package:api/Service/remote_service.dart';
import 'package:api/model/post.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Post>? posts;
var isLoaded = false;
@override
void initState() {
super.initState();
getData();
}
getData() async {
posts = (await RemoteService().getPost())?.cast<Post>();
if (posts != null) {
setState(() {
isLoaded = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sample API'),
),
body: ListView.builder(
itemCount: posts?.length,
itemBuilder: (context, index) {
return Container(
child: Text(posts![index].title),
);
}),
);
}
}
model.dart
// To parse this JSON data, do
//
// final Post = PostFromJson(jsonString);
import 'dart:convert';
List<Post?>? PostFromJson(String str) => json.decode(str) == null
? []
: List<Post?>.from(json.decode(str)!.map((x) => Post.fromJson(x)));
String PostToJson(List<Post?>? data) => json.encode(
data == null ? [] : List<dynamic>.from(data.map((x) => x!.toJson())));
class Post {
Post({
required this.userId,
required this.id,
required this.title,
this.body,
});
int userId;
int id;
String title;
String? body;
factory Post.fromJson(Map<String, dynamic> json) => Post(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}
remote-service.dart
import 'package:api/model/post.dart';
import 'package:http/http.dart' as http;
class RemoteService {
Future<List<Post?>?> getPost() async {
var client = http.Client();
var uri = Uri.parse("https://jsonplaceholder.typicode.com/posts");
var response = await client.get(uri);
if (response.statusCode == 200) {
var json = response.body;
return PostFromJson(json);
}
}
}
Comments
Post a Comment