Handling and Displaying List Data from an API in Flutter

 

Introduction

  • Briefly introduce the topic and explain why handling and displaying list data from an API is a common and useful task in Flutter development.

Step 1: Setting Up Your Flutter Project

  • Explain how to create a new Flutter project using flutter create project_name.
  • Mention adding the http dependency in pubspec.yaml.
dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3


class StatusItem {
final int id;
final String value;
final String label;
final int status;
final int sequence;
final String? deletedAt;
final String createdAt;
final String updatedAt;

StatusItem({
required this.id,
required this.value,
required this.label,
required this.status,
required this.sequence,
this.deletedAt,
required this.createdAt,
required this.updatedAt,
});

factory StatusItem.fromJson(Map<String, dynamic> json) {
return StatusItem(
id: json['id'],
value: json['value'],
label: json['label'],
status: json['status'],
sequence: json['sequence'],
deletedAt: json['deleted_at'],
createdAt: json['created_at'],
updatedAt: json['updated_at'],
);
}
}



Step 3: Fetch Data from the API

  • Explain how to fetch data from the API using the http package and parse it into a list of StatusItem objects.


import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
late Future<List<StatusItem>> futureApiResponse;

@override
void initState() {
super.initState();
futureApiResponse = fetchApiResponse();
}

Future<List<StatusItem>> fetchApiResponse() async {
final url = "http://urbanflowservice.hirenow.co.in/api/booking-status";
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
List<dynamic> body = jsonDecode(response.body);
List<StatusItem> statuses = body.map((dynamic item) => StatusItem.fromJson(item)).toList();
return statuses;
} else {
throw Exception('Failed to load data');
}
} catch (error) {
rethrow;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Data'),
),
body: FutureBuilder<List<StatusItem>>(
future: futureApiResponse,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final item = snapshot.data![index];
return ListTile(
title: Text(item.label),
subtitle: Text('Value: ${item.value}, Status: ${item.status}'),
);
},
);
} else {
return Center(child: Text('No data found'));
}
},
),
);
}
}



Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

HTTP GET Response in Flutter

Building a Flutter Firebase Firestore CRUD App