Integrating GET API with Provider in Flutter
Explanation
In Flutter, Provider is a simple and effective state management solution. You can use it to manage data and
notify UI when changes occur.
Steps:
1. Add provider and http packages to pubspec.yaml.
2. Create a ChangeNotifier class to handle fetching and storing data.
3. Provide the ChangeNotifier in the widget tree using ChangeNotifierProvider.
4. Use Consumer or context.watch to respond to changes in the UI.
Example Code
// post_provider.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class PostProvider with ChangeNotifier {
String? _title;
bool _isLoading = false;
String? get title => _title;
bool get isLoading => _isLoading;
Future<void> fetchPost() async {
_isLoading = true;
notifyListeners();
try {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
final data = json.decode(response.body);
_title = data['title'];
} else {
_title = 'Failed to fetch data';
}
} catch (e) {
_title = 'Error occurred';
}
Integrating GET API with Provider in Flutter
_isLoading = false;
notifyListeners();
}
}
// main_widget.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class PostPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => PostProvider()..fetchPost(),
child: Scaffold(
appBar: AppBar(title: Text('GET API with Provider')),
body: Consumer<PostProvider>(
builder: (context, postProvider, _) {
if (postProvider.isLoading) {
return Center(child: CircularProgressIndicator());
} else {
return Center(child: Text(postProvider.title ?? '', style: TextStyle(fontSize:
18)));
}
},
),
),
);
}
}