0% found this document useful (0 votes)
2 views

Step 1

This document outlines the steps to create a Flutter project that fetches data from a public API using the http package. It includes instructions for setting up the project, adding dependencies, creating an API service, building a user interface with FutureBuilder, and running the app. The example uses JSONPlaceholder to display a list of posts fetched from the API.

Uploaded by

ankitkumawat061
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Step 1

This document outlines the steps to create a Flutter project that fetches data from a public API using the http package. It includes instructions for setting up the project, adding dependencies, creating an API service, building a user interface with FutureBuilder, and running the app. The example uses JSONPlaceholder to display a list of posts fetched from the API.

Uploaded by

ankitkumawat061
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Step 1: Create a Flutter Project

1. Create a new Flutter project:

bash
Copy code
flutter create api_fetch_example
cd api_fetch_example

2. Open the project in your preferred IDE (e.g., Visual Studio Code or Android Studio).

Step 2: Add Dependencies

1. Open pubspec.yaml.
2. Add the http package for API requests:

yaml
Copy code
dependencies:
http: ^1.0.0

3. Run flutter pub get to install the package.

Step 3: Fetch Data from API

1. Use a public API like JSONPlaceholder for example purposes.


2. Create a service file to handle API calls.

File: lib/api_service.dart

dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService {
static const String baseUrl = "https://jsonplaceholder.typicode.com";

Future<List<dynamic>> fetchPosts() async {


final response = await http.get(Uri.parse('$baseUrl/posts'));

if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to load posts');
}
}
}

Step 4: Create the UI

1. Display the fetched data using FutureBuilder.

File: lib/main.dart

dart
Copy code
import 'package:flutter/material.dart';
import 'api_service.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'API Fetch Example',
theme: ThemeData(primarySwatch: Colors.blue),
home: HomePage(),
);
}
}

class HomePage extends StatelessWidget {


final ApiService apiService = ApiService();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Fetch Example'),
),
body: FutureBuilder<List<dynamic>>(
future: apiService.fetchPosts(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return Center(child: Text('No data available.'));
}

final posts = snapshot.data!;


return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
final post = posts[index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);
},
);
},
),
);
}
}

Step 5: Run the App

1. Run the app:

bash
Copy code
flutter run

2. You should see a list of posts displayed from the API.

Explanation

1. HTTP Request: The http.get() method fetches data from the API.
2. JSON Parsing: The response is parsed using jsonDecode().
3. FutureBuilder: Dynamically updates the UI based on the API response.

You might also like