cft

Get request in flutter

An article on how to make get requests in flutter using http package


user

Aditya Subrahmanya Bhat

3 years ago | 1 min read

Whenever we need to make a get request, we need to communicate with the database using http protocol.

Flutter cannot make http calls on its own. So we use a package named 'http'.

https://pub.dev/packages/http

We'll be using JSONPlaceholder API to make a get request in our app.

https://jsonplaceholder.typicode.com/

Let's create an app using flutter.

Change the main.dart to this

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}

Add the http package to pubspec.yaml file.

pubspec.yaml
pubspec.yaml

Now create a new page. I'll be naming it homePage.dart

homePage.dart
homePage.dart

Making the API call

The APICall() function is where we will be making the http call.

Future<Response> APICall() async {
try {
Uri url = Uri.parse('https://jsonplaceholder.typicode.com/users');
Response response = await http.get(url);
return response;
} catch (e) {
return null;
}
}

The http.get() function is used to make the get request and it takes the parsed url as an argument. You can also pass headers if necessary. Since the function cannot take the url string directly, it has to be parsed into a URI (a parsed URI such as URL). The http.get() function returns a Future of type Response, so we await the function and return the response.


Now, let's call the function inside the onPressed function of the button.

onPressed: () async {
setState(() {
loading = true;
});
Response response = await APICall();
setState(() {
users = response.body;
loading = false;
});
},

Once the http call is made, we will be displaying the data it returned, on the home page.

Well, That's all folks 😊 Thank you.

Upvote


user
Created by

Aditya Subrahmanya Bhat


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles