In this blog, we will learn how to make Networking and Connecting to API in Flutter and how to handle that response properly. Throughout this tutorial, we will learn how to do that by building a Flutter app.
While building an app that fetches data from the internet or posts some data over a server, we need the network calling in the App.
Throughout this blog, you’ll learn the following things:
- Locally deploying a RESTFUL API.
- Making GET, POST, and DELETE requests.
- Using an HTTP client to make the network request.
- Handling different states like Loading, Success, and Error.
Network Request
A network request is a request for data from a server that will display inside the App.
RESTful API
It’s an application program interface (API) that uses HTTP requests to get or send data between two locations.
Firstly, the client requests the server for the data, meanwhile, the server checks the request and sends the requested data to the client.
HTTP Methods
There are four main HTTP methods that will use in REST APIs.
- Get
- Post
- Put
- Delete
We are discussing here the Get request of the HTTP method.
1. Make the network call to the Server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fetchData() async { Uri url = Uri.parse("https://jsonplaceholder.typicode.com/posts"); var response = await http.get(url); if (response.statusCode == 200) { var data = json.decode(response.body); setState(() { for (var i in data) { listOfName.add(UserModel.fromJson(i)); } isLoading = false; }); } return listOfName; } |
2. Make the Model class to store the response that we will get from the API call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class UserModel{ int id; String title; String body; UserModel({required this.id,required this.title,required this.body}); factory UserModel.fromJson(Map<String, dynamic> parsedjson) { return UserModel( id:parsedjson["id"], title: parsedjson["title"], body: parsedjson['body'] ); } } |
3. Make the UI according to your requirements, here I display the title from the response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "LIST OF DATA", style: TextStyle(color: Colors.black), ), ), body: Center( child: isLoading ? const CircularProgressIndicator() : ListView.builder( itemCount: listOfName.length, itemBuilder: (context, index) { return Container( padding: const EdgeInsets.all(15.0), child: Text( listOfName[index].title, style: const TextStyle( color: Colors.brown, fontSize: 15, fontWeight: FontWeight.bold), ), ); }), ), ); } |
Output:-
Conclusion
Congratulation!! In this blog, we have implemented Networking and Connecting to API in flutter.
I hope it will help you out in understanding and getting a brief about it.
Similarly, for more interesting blogs check out here – here
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Thanks for reading!!.