import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
class AdvancedHttpScreen extends StatefulWidget {
@override
State<AdvancedHttpScreen> createState() => _AdvancedHttpScreenState();
}
class _AdvancedHttpScreenState extends State<AdvancedHttpScreen> {
final Dio dio = Dio();
String status = 'Idle';
String responseText = '';
@override
void initState() {
super.initState();
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
print('Request: ${options.method} ${options.uri}');
return handler.next(options);
},
onResponse: (response, handler) {
print('Response: ${response.statusCode} ${response.data}');
return handler.next(response);
},
onError: (DioError e, handler) {
print('Error: ${e.message}');
return handler.next(e);
},
));
}
Future<void> fetchData() async {
setState(() {
status = 'Loading...';
responseText = '';
});
try {
final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');
setState(() {
status = 'Success';
responseText = response.data.toString();
});
} catch (e) {
setState(() {
status = 'Error';
responseText = e.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Advanced HTTP with Dio')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: fetchData,
child: Text('Fetch Data'),
),
SizedBox(height: 20),
Text('Status: $status'),
SizedBox(height: 20),
Expanded(
child: SingleChildScrollView(
child: Text(responseText),
),
),
],
),
),
);
}
}
We added Dio interceptors in initState to print request, response, and error details to the console. This helps us see what is happening behind the scenes.
The fetchData method uses Dio to make a GET request to a sample API. It updates the UI state to show loading, success, or error messages. The response data is shown as a string in a scrollable area.
This approach teaches how to handle advanced HTTP features like interceptors and error handling with Dio in Flutter.