Integrating GET API with setState in Flutter
Explanation
In Flutter, integrating a GET API with setState involves making an HTTP request using a package like 'http'
and updating the UI once the data is fetched. This is typically done inside the initState() or triggered by user
actions.
Here's the general flow:
1. Add the http package to your [Link].
2. Create a function that fetches data from the API.
3. Use setState to update your widget's state after receiving the data.
Example Code
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;
import 'dart:convert';
class GetApiWithSetState extends StatefulWidget {
@override
_GetApiWithSetStateState createState() => _GetApiWithSetStateState();
}
class _GetApiWithSetStateState extends State<GetApiWithSetState> {
String? data;
@override
void initState() {
[Link]();
fetchData();
}
Future<void> fetchData() async {
final response = await [Link]([Link]('[Link]
if ([Link] == 200) {
final jsonData = [Link]([Link]);
setState(() {
data = jsonData['title'];
});
} else {
Integrating GET API with setState in Flutter
setState(() {
data = 'Failed to fetch data';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('GET API with setState')),
body: Center(
child: data == null
? CircularProgressIndicator()
: Text(data!, style: TextStyle(fontSize: 18)),
),
);
}
}