Step 1
Step 1
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).
1. Open pubspec.yaml.
2. Add the http package for API requests:
yaml
Copy code
dependencies:
http: ^1.0.0
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";
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to load posts');
}
}
}
File: lib/main.dart
dart
Copy code
import 'package:flutter/material.dart';
import 'api_service.dart';
void main() {
runApp(MyApp());
}
@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.'));
}
bash
Copy code
flutter run
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.