0% found this document useful (0 votes)
3 views

library-app.dart

The document contains Dart code for a library management system using Supabase. It defines a 'Book' model with methods for JSON serialization, a 'BookService' class for managing book data (adding, retrieving, updating availability, and deleting books), and a 'BooksScreen' widget that displays a list of books with real-time updates. The UI allows users to toggle book availability and delete books through a dialog prompt.

Uploaded by

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

library-app.dart

The document contains Dart code for a library management system using Supabase. It defines a 'Book' model with methods for JSON serialization, a 'BookService' class for managing book data (adding, retrieving, updating availability, and deleting books), and a 'BooksScreen' widget that displays a list of books with real-time updates. The UI allows users to toggle book availability and delete books through a dialog prompt.

Uploaded by

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

// book_model.

dart
import 'package:supabase_flutter/supabase_flutter.dart';

class Book {
final String id;
final String title;
final String author;
final DateTime publishedDate;
bool isAvailable;

Book({
required this.id,
required this.title,
required this.author,
required this.publishedDate,
required this.isAvailable,
});

factory Book.fromJson(Map<String, dynamic> json) {


return Book(
id: json['id'],
title: json['title'],
author: json['author'],
publishedDate: DateTime.parse(json['published_date']),
isAvailable: json['is_available'],
);
}

Map<String, dynamic> toJson() {


return {
'id': id,
'title': title,
'author': author,
'published_date': publishedDate.toIso8601String(),
'is_available': isAvailable,
};
}
}

// book_service.dart
class BookService {
final SupabaseClient supabase;

BookService(this.supabase);

// Menambahkan buku baru


Future<Book> addBook(Book book) async {
final response = await supabase
.from('books')
.insert(book.toJson())
.select()
.single();

return Book.fromJson(response);
}

// Mengambil semua buku


Future<List<Book>> getAllBooks() async {
final response = await supabase
.from('books')
.select()
.order('title');

return response.map((json) => Book.fromJson(json)).toList();


}

// Memperbarui status ketersediaan buku


Future<void> updateBookAvailability(String id, bool isAvailable) async {
await supabase
.from('books')
.update({'is_available': isAvailable})
.eq('id', id);
}

// Menghapus buku
Future<void> deleteBook(String id) async {
await supabase
.from('books')
.delete()
.eq('id', id);
}

// Subscribe ke perubahan real-time


Stream<List<Book>> getBooksStream() {
return supabase
.from('books')
.stream(primaryKey: ['id'])
.map((list) => list.map((json) => Book.fromJson(json)).toList());
}
}

// books_screen.dart
class BooksScreen extends StatefulWidget {
@override
_BooksScreenState createState() => _BooksScreenState();
}

class _BooksScreenState extends State<BooksScreen> {


final BookService _bookService = BookService(Supabase.instance.client);
late Stream<List<Book>> _booksStream;

@override
void initState() {
super.initState();
_booksStream = _bookService.getBooksStream();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Library Management'),
),
body: StreamBuilder<List<Book>>(
stream: _booksStream,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}

if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}

final books = snapshot.data!;

return ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
final book = books[index];
return ListTile(
title: Text(book.title),
subtitle: Text(book.author),
trailing: Switch(
value: book.isAvailable,
onChanged: (bool value) {
_bookService.updateBookAvailability(book.id, value);
},
),
onLongPress: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Delete Book'),
content: Text('Are you sure you want to delete this book?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
),
TextButton(
onPressed: () {
_bookService.deleteBook(book.id);
Navigator.pop(context);
},
child: Text('Delete'),
),
],
),
);
},
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Implement add book dialog/screen
},
child: Icon(Icons.add),
),
);
}
}

You might also like