【AI×アプリ開発】書籍管理アプリソースコード全容 その4(⑥終了時点)
こちらは、AIにアプリ開発を丸投げしている記事のソースコードです。
今回は、以下記事で作った部分のソースコード公開です。
本一覧画面を新規作成し、表示できるようにしました。
完成版ではないので、今後の開発で記載内容は随時変わっていきます。
それをご了承の上、閲覧及び組み込みください。
また、作成中のソースコードなのでまだ言うべきことではないでしょうが、
コードをコピペして作成したアプリの商用利用はご遠慮ください。
ではいってみましょう。
lib配下ディレクトリ構成
.
├── core
│ ├── utils
│ │ ├── app_colors.dart
│ │ └── app_tabs.dart
│ └── widgets
│ ├── footer.dart
│ ├── header.dart
│ ├── widget_count_book.dart
│ ├── widget_empty_state.dart
│ ├── widget_list_row.dart
│ └── widget_loading_center.dart
├── data
│ ├── models
│ │ ├── book.dart
│ │ ├── category.dart
│ │ └── publisher.dart
│ └── repositories
│ ├── common.dart
│ └── select_repository.dart
├── pages
│ ├── add
│ ├── list
│ │ ├── list_book.dart
│ │ ├── list_category.dart
│ │ └── list_publisher.dart
│ ├── search
│ ├── setting
│ ├── wish
│ └── root_page.dart
└── main.dart新規追加
book.dart
class Book {
final String imageUrl;
final String title;
final String titleKana;
final String isbn;
final String author;
final String authorKana;
final String publisher;
final String size;
final String series;
final String seriesKana;
final String salesDate;
final int price;
final String notes;
Book({
required this.imageUrl,
required this.title,
required this.titleKana,
required this.isbn,
required this.author,
required this.authorKana,
required this.publisher,
required this.size,
required this.series,
required this.seriesKana,
required this.salesDate,
required this.price,
required this.notes,
});
factory Book.fromMap(Map<String, dynamic> map) {
return Book(
imageUrl: map['url'] ?? '',
title: map['title'] ?? '',
titleKana: map['title_kana'] ?? '',
isbn: map['isbn'] ?? '',
author: map['author'] ?? '',
authorKana: map['author_kana'] ?? '',
publisher: map['publisher'] ?? '',
size: map['size'] ?? '',
series: map['series'] ?? '',
seriesKana: map['series_kana'] ?? '',
salesDate: map['sales_date'] ?? '',
price: map['price'] ?? 0,
notes: map['notes'] ?? '',
);
}
}list_book.dart
import 'package:book_app/core/utils/app_colors.dart';
import 'package:book_app/core/widgets/widget_empty_state.dart';
import 'package:book_app/core/widgets/widget_list_row.dart';
import 'package:book_app/core/widgets/widget_loading_center.dart';
import 'package:book_app/data/models/book.dart';
import 'package:book_app/data/models/category.dart';
import 'package:book_app/data/models/publisher.dart';
import 'package:book_app/data/repositories/common.dart';
import 'package:book_app/data/repositories/select_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ListBookPage extends ConsumerWidget {
final Category category;
final Publisher publisher;
final void Function(Book)? onSelectBook;
const ListBookPage({
super.key,
required this.category,
required this.publisher,
required this.onSelectBook,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final bookAsync = ref.watch(databaseProvider);
return bookAsync.when(
// 本一覧取得
data: (db) => FutureBuilder<List<Book>>(
future: fetchBook(db, category.cId, publisher.pId),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const LoadingCenter();
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final books = snapshot.data ?? [];
if (books.isEmpty) {
return const EmptyState(message: 'Book not found');
}
// データ表示
return ListView.separated(
itemCount: books.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, index) {
final b = books[index];
return ListRow(
leading: (b.imageUrl.isNotEmpty)
? Image.network(
b.imageUrl,
width: 60,
height: 60,
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.book_sharp, color: AppColors.primaryText, size: 60);
},
)
: const Icon(Icons.book_sharp, color: AppColors.primaryText, size: 60),
title: Text(b.title,
style: const TextStyle(color: AppColors.primaryText, fontSize: 16, fontWeight: FontWeight.bold,)
),
subtitle: Text('${b.author}\n${b.salesDate}',
style: const TextStyle(color: AppColors.primaryText, fontSize: 14)
),
onTap: () => onSelectBook?.call(b),
);
},
);
},
),
loading: () => const LoadingCenter(),
error: (err, _) => Center(child: Text('Error: $err')),
);
}
}変更
app_tabs.dart
enum AppView { categories, publishers, books, detail, search, add, wish }
const List<AppView> tabTopViews = [
AppView.categories,
AppView.search,
AppView.add,
AppView.wish,
];select_repository.dart
import 'package:book_app/data/models/book.dart';
import 'package:book_app/data/models/publisher.dart';
import 'package:sqflite/sqflite.dart';
import '../models/category.dart';
// 分類一覧取得
Future<List<Category>> fetchCategory(Database db) async {
final result = await db.rawQuery('''
SELECT c.c_id c_id, c.c_name c_name, count(*) c_count
FROM m_category c
INNER JOIN t_book b ON c.c_id = b.c_id
GROUP BY c.c_id
''');
return result.map((row) => Category.fromMap(row)).toList();
}
// 出版社一覧取得
Future<List<Publisher>> fetchPublisher(Database db, int cId) async {
final result = await db.rawQuery('''
SELECT p.p_id p_id, p.p_name p_name, count(*) p_count
FROM m_publisher p
INNER JOIN t_book b ON p.p_id = b.p_id
WHERE b.c_id = ?
GROUP BY p.p_id
''', [cId]);
return result.map((row) => Publisher.fromMap(row)).toList();
}
// 本一覧取得
Future<List<Book>> fetchBook(Database db, int cId, int pId) async {
final result = await db.rawQuery(
'''
SELECT isbn, url, title, author, sales_date
FROM t_book
WHERE c_id = ? AND p_id = ?
ORDER BY author_kana, title_kana, sales_date
''',
[cId, pId],
);
return result.map((row) => Book.fromMap(row)).toList();
}root_page.dart
import 'package:book_app/core/utils/app_tabs.dart';
import 'package:book_app/core/widgets/footer.dart';
import 'package:book_app/core/widgets/header.dart';
import 'package:book_app/data/models/book.dart';
import 'package:book_app/data/models/category.dart';
import 'package:book_app/data/models/publisher.dart';
import 'package:book_app/pages/list/list_book.dart';
import 'package:book_app/pages/list/list_category.dart';
import 'package:book_app/pages/list/list_publisher.dart';
import 'package:flutter/material.dart';
// ダミーページ
class SearchPage extends StatelessWidget {
const SearchPage({super.key});
@override Widget build(BuildContext c) => const Center(child: Text('Search'));
}
class AddPage extends StatelessWidget {
const AddPage({super.key});
@override Widget build(BuildContext c) => const Center(child: Text('Add'));
}
class WishPage extends StatelessWidget {
const WishPage({super.key});
@override Widget build(BuildContext c) => const Center(child: Text('Wish'));
}
class SettingPage extends StatelessWidget {
const SettingPage({super.key});
@override Widget build(BuildContext c) => Scaffold(appBar: AppHeader(title: 'Setting'), body: const Center(child: Text('Setting')));
}
class RootPage extends StatefulWidget {
const RootPage({super.key});
@override
State<RootPage> createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
AppView _view = AppView.categories;
int _currentIndex = 0;
Category? _selectedCategory;
Publisher? _selectedPublisher;
// 画面タイトル
String _getTitle() {
switch (_view) {
case AppView.categories:
return 'List_Category';
case AppView.publishers:
return 'List_Publisher';
case AppView.books:
return 'List_Book';
case AppView.detail:
return 'List_Detail';
case AppView.search:
return 'Search_Book';
case AppView.add:
return 'Add_Top';
case AppView.wish:
return 'Wish_Top';
}
}
// 現在のタブのトップ画面かどうか
bool _isTopLevel() => _view == tabTopViews[_currentIndex];
void _setTab(int index) {
setState(() {
_currentIndex = index;
_view = tabTopViews[index];
if (_view != AppView.publishers) _selectedCategory = null;
});
}
// Category→Publisher
void _openPublishers(Category category) {
setState(() {
_selectedCategory = category;
_view = AppView.publishers;
});
}
// Publisher→Book
void _openBooks(Publisher publisher) {
setState(() {
_selectedPublisher = publisher;
_view = AppView.books;
});
}
// Book→Detail
void _openDetail(Book book) {
setState(() {
_view = AppView.detail;
});
}
// Back
void _onHeaderBack() {
setState(() {
if (_view == AppView.books) {
_view = AppView.publishers;
} else if (_view == AppView.publishers) {
_view = AppView.categories;
} else {
if (Navigator.canPop(context)) Navigator.pop(context);
}
});
}
// Body
Widget _buildBody() {
switch (_view) {
case AppView.categories:
return ListCategoryPage(onSelectCategory: _openPublishers);
case AppView.publishers:
if (_selectedCategory == null) return ListCategoryPage(onSelectCategory: _openPublishers);
return ListPublisherPage(category: _selectedCategory!, onSelectPublisher: _openBooks);
case AppView.books:
if (_selectedPublisher == null) return ListPublisherPage(category: _selectedCategory!, onSelectPublisher: _openBooks);
return ListBookPage(category: _selectedCategory!, publisher: _selectedPublisher!, onSelectBook: _openDetail);
//return const Center(child: Text('List_Book'));
case AppView.detail:
return const Center(child: Text('List_Detail'));
case AppView.search:
return const SearchPage();
case AppView.add:
return const AddPage();
case AppView.wish:
return const WishPage();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppHeader(
title: _getTitle(),
onBack: _isTopLevel() ? null : _onHeaderBack,
onSetting: () {
Navigator.push(context, MaterialPageRoute(builder: (_) => const SettingPage()));
},
),
body: _buildBody(),
bottomNavigationBar: AppFooter(currentIndex: _currentIndex, onTap: _setTab),
);
}
}おわり
今回は以上となります。
また、次回以降も見ていただけると幸いです。