API_example
Step 1: Add the http package to pubspec.yaml:
http package to pubspec.yaml:dependencies:
flutter:
sdk: flutter
http: ^0.14.0Step 2: Make HTTP requests:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// Function to fetch data from the API
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON response
return json.decode(response.body);
} else {
// If the call to the server was unsuccessful, throw an error
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('API Demo'),
),
body: Center(
child: FutureBuilder<List<dynamic>>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
// Display the fetched data
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data![index]['title']),
subtitle: Text(snapshot.data![index]['description']),
);
},
);
} else if (snapshot.hasError) {
// Show error message if request fails
return Text('Error: ${snapshot.error}');
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}Important Points:
Last updated