0% found this document useful (0 votes)
5 views2 pages

Flutter GetAPI SetState Example

The document explains how to integrate a GET API with setState in Flutter by making an HTTP request using the 'http' package and updating the UI with the fetched data. It outlines the steps to add the package, create a data-fetching function, and use setState to update the widget's state. An example code snippet demonstrates the implementation within a StatefulWidget, including error handling for failed requests.

Uploaded by

mayuraimaker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Flutter GetAPI SetState Example

The document explains how to integrate a GET API with setState in Flutter by making an HTTP request using the 'http' package and updating the UI with the fetched data. It outlines the steps to add the package, create a data-fetching function, and use setState to update the widget's state. An example code snippet demonstrates the implementation within a StatefulWidget, including error handling for failed requests.

Uploaded by

mayuraimaker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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)),
),
);
}
}

You might also like