How to GET request in the Flutter app

Gaurab Roy
2 min readFeb 2, 2023

--

Flutter Logo

Here are the steps to create a Flutter app with a GET request using a REST API:

  1. Set up a new Flutter project in your preferred IDE.
  2. Choose an API to connect to, or create your own REST API.
  3. Add the required dependencies http for making HTTP requests in the pubspec.yaml file for making HTTP requests.
  4. 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 ]
  5. Create a data repository to handle the API's fetching and storing of data.
  6. Create the UI for your app, using widgets such as TextField, ListView, and RaisedButton for creating, updating, and deleting data.
  7. In your main.dart file, create the logic for making API calls to perform CRUD operations.
  8. 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.

--

--

Gaurab Roy
Gaurab Roy

No responses yet