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 pubspec.yaml.
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/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class GetApiWithSetState extends StatefulWidget {
@override
_GetApiWithSetStateState createState() => _GetApiWithSetStateState();
}
class _GetApiWithSetStateState extends State<GetApiWithSetState> {
String? data;
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
final jsonData = json.decode(response.body);
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)),
),
);
}
}