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 [Link].
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 [Link] to respond to changes in the UI.
Example Code
// post_provider.dart
import 'package:flutter/[Link]';
import 'package:http/[Link]' 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 [Link]([Link]('[Link]
if ([Link] == 200) {
final data = [Link]([Link]);
_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/[Link]';
import 'package:provider/[Link]';
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 ([Link]) {
return Center(child: CircularProgressIndicator());
} else {
return Center(child: Text([Link] ?? '', style: TextStyle(fontSize:
18)));
}
},
),
),
);
}
}