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

Flutter Book Fetching App Code

Uploaded by

Kinza Fatima
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)
4 views5 pages

Flutter Book Fetching App Code

Uploaded by

Kinza Fatima
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

class Book {

final int id;


final String title;
final String author;
final String coverUrl;

Book({
required [Link],
required [Link],
required [Link],
required [Link],
});

// Factory constructor for creating a Book from JSON data


factory [Link](Map<String, dynamic> json) => Book(
id: json['id'],
title: json['title'],
author: json['author'],
coverUrl: json['coverUrl'],
);
}
import 'dart:convert';
import 'package:http/[Link]' as http;

Future<List<Book>> fetchBooks() async {


final url = [Link]('[Link]

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

if ([Link] == 200) {
final List<dynamic> bookJson = jsonDecode([Link]);
return [Link]((json) => [Link](json)).toList();
} else {
throw Exception('Failed to load books. Status code:
${[Link]}');
}
} catch (e) {
throw Exception('Error fetching books: $e');
}
}
import 'package:flutter/[Link]';

class BookApp extends StatelessWidget {


const BookApp({[Link]});

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Books'),
),
body: const BookGrid(),
),
);
}
}

class BookGrid extends StatelessWidget {


const BookGrid({[Link]});

@override
Widget build(BuildContext context) {
return FutureBuilder<List<Book>>(
future: fetchBooks(),
builder: (context, snapshot) {
if ([Link] == [Link]) {
return const Center(
child: CircularProgressIndicator(),
);
} else if ([Link]) {
return Center(
child: Text('Error: ${[Link]}'),
);
} else if ([Link]) {
final books = [Link]!;
return [Link](
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: [Link],
itemBuilder: (context, index) {
return BookCard(book: books[index]);
},
);
} else {
return const Center(
child: Text('No books available'),
);
}
},
);
}
}

class BookCard extends StatelessWidget {


final Book book;

const BookCard({required [Link], [Link]});

@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
[Link](
[Link],
height: 100,
fit: [Link],
),
Padding(
padding: const [Link](vertical: 8.0),
child: Text(
[Link],
style: const TextStyle(fontWeight: [Link]),
),
),
Text([Link]),
],
),
);
}
}
void main() {
runApp(const BookApp());
}

You might also like