0% found this document useful (0 votes)
11 views5 pages

Fetch and Display API Data in Flutter

The document describes a Flutter application that fetches data from a REST API and displays it in a user-friendly manner. It includes code snippets for setting up dependencies, fetching data, and creating a custom widget for displaying posts. The application handles loading states and errors while presenting the fetched data in a structured layout using cards.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

Fetch and Display API Data in Flutter

The document describes a Flutter application that fetches data from a REST API and displays it in a user-friendly manner. It includes code snippets for setting up dependencies, fetching data, and creating a custom widget for displaying posts. The application handles loading states and errors while presenting the fetched data in a structured layout using cards.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab Session 9:

a) Fetch data from REST API add dependancy in [Link]:


dependencies:
flutter:
sdk: flutter
http: ^0.13.3

import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


List<Map<String, dynamic>> _data = [];
bool _isLoading = true;
String? _error;

@override
void initState() {
[Link]();
_fetchDataFromApi();
}

Future<void> _fetchDataFromApi() async {


try {
final response = await [Link](
[Link]('[Link]
);

if ([Link] == 200) {
setState(() {
_data = List<Map<String,
dynamic>>.from([Link]([Link]));
_isLoading = false;
});
} else {
setState(() {
_error = 'Failed to load data (status $
{[Link]})';
_isLoading = false;
});
}
} catch (e) {
setState(() {
_error = 'Error: $e';
_isLoading = false;
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Data Example')),
body: _isLoading
? Center(child: CircularProgressIndicator())
: _error != null
? Center(child: Text(_error!))
: [Link](
itemCount: _data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_data[index]['title']),
subtitle: Text(_data[index]['body']),
);
},
),
);
}
}
b) Display the fetched data in a meaningful way in the UI
display the fetched data in a meaningful way in the UI, we can use a more structured layout
rather than just displaying the data in a list. We'll create a custom widget to represent each
post fetched from the API, and display them in a scrollable list.

dependencies:
flutter:
sdk: flutter
http: ^0.13.6

import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


List<dynamic> _data = [];
bool _isLoading = false;

@override
void initState() {
[Link]();
_fetchDataFromApi();
}

Future<void> _fetchDataFromApi() async {


setState(() {
_isLoading = true;
});
final response = await [Link](
[Link]('[Link]
);
if ([Link] == 200) {
setState(() {
_data = [Link]([Link]);
_isLoading = false;
});
} else {
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Data Example')),
body: _isLoading
? Center(child: CircularProgressIndicator())
: [Link](
itemCount: _data.length,
itemBuilder: (context, index) {
return PostCard(
title: _data[index]['title'],
body: _data[index]['body'],
);
},
),
);
}
}

class PostCard extends StatelessWidget {


final String title;
final String body;

const PostCard({[Link], required [Link], required


[Link]});

@override
Widget build(BuildContext context) {
return Card(
margin: [Link](horizontal: 16, vertical: 8),
child: Padding(
padding: [Link](16),
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
Text(
title,
style: TextStyle(fontSize: 18, fontWeight:
[Link]),
),
SizedBox(height: 8),
Text(body, style: TextStyle(fontSize: 16)),
],
),
),
);
}
}

You might also like