How to GET request in the Flutter app
2 min readFeb 2, 2023
Here are the steps to create a Flutter app with a GET request using a REST API:
- Set up a new Flutter project in your preferred IDE.
- Choose an API to connect to, or create your own REST API.
- Add the required dependencies
http
for making HTTP requests in thepubspec.yaml
file for making HTTP requests. - Create a model class to represent the data you will be working with.
[Note: To create a model class you can refer to https://app.quicktype.io ] - Create a data repository to handle the API's fetching and storing of data.
- Create the UI for your app, using widgets such as
TextField
,ListView
, andRaisedButton
for creating, updating, and deleting data. - In your
main.dart
file, create the logic for making API calls to perform CRUD operations. - Test the app to ensure that it is correctly performing the CRUD operations.
Here is an example of a simple CRUD operation in Flutter using the http
package:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter CRUD with REST API',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final String apiUrl = "https://jsonplaceholder.typicode.com/posts";
List data;
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
var res = await http.get(apiUrl);
setState(() {
data = jsonDecode(res.body);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter CRUD with REST API'),
),
body: data != null
? ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(data[index]['title']),
),
);
},
)
: Center(
child: CircularProgressIndicator(),
),
);
}
}
This example demonstrates how to fetch data from a REST API and display it in a ListView
widget in Flutter. You can modify this code to implement the other CRUD operations per your requirements.