メインコンテンツへスキップ

【AI×アプリ開発】書籍管理アプリソースコード全容 その3(⑤終了時点)

    こちらは、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
    │   │   ├── category.dart
    │   │   └── publisher.dart              // 追加
    │   └── repositories
    │       ├── common.dart
    │       └── select_repository.dart      // 変更(元ファイル名:category_repository.dart)
    ├── pages
    │   ├── add
    │   ├── list
    │   │   ├── list_category.dart          // 変更
    │   │   └── list_publisher.dart         // 追加
    │   ├── search
    │   ├── setting
    │   ├── wish
    │   └── root_page.dart                   // 追加
    └── main.dart                            // 変更

    新規追加

    list_publisher.dart

    import 'package:book_app/core/utils/app_colors.dart';
    import 'package:book_app/core/widgets/widget_count_book.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/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 ListPublisherPage extends ConsumerWidget {
      final Category category;
      final void Function(Publisher)? onSelectPublisher;
      
      const ListPublisherPage({
        super.key,
        required this.category,
        this.onSelectPublisher,
      });
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final publisherAsync = ref.watch(databaseProvider);
    
        return publisherAsync.when(
          // 出版社一覧取得
          data: (db) => FutureBuilder<List<Publisher>>(
            future: fetchPublisher(db, category.cId),
            builder: (context, snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
                return const LoadingCenter();
              }
              if (snapshot.hasError) {
                return Center(child: Text('Error: ${snapshot.error}'));
              }
              final publishers = snapshot.data ?? [];
              if (publishers.isEmpty) {
                return const EmptyState(message: 'Publisher not found');
              }
    
              // リスト表示
              return ListView.separated(
                itemCount: publishers.length,
                separatorBuilder: (_, __) => const Divider(height: 1),
                itemBuilder: (context, index) {
                  final p = publishers[index];
                  return ListRow(
                    leading: Icon(Icons.folder_sharp, color: AppColors.primaryText, size: 45),
                    title: Text(p.pName,
                    style: const TextStyle(color: AppColors.primaryText, fontSize: 18)),
                    trailing: CountBook(count: p.pCount),
                    onTap: () => onSelectPublisher?.call(p),
                  );
                },
              );
            },
          ),
          loading: () => const LoadingCenter(),
          error: (err, _) => Center(child: Text('Error: $err')),
        );
      }
    }

    root_page.dart

    // lib/pages/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/category.dart';
    import 'package:book_app/data/models/publisher.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;
    
      // 画面タイトル
      String _getTitle() {
        switch (_view) {
          case AppView.categories:
            return 'List_Category';
          case AppView.publishers:
            return 'List_Publisher';
          case AppView.books:
            return 'List_Book';
          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(() {
          _view = AppView.books;
        });
      }
    
      // 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:
            return const Center(child: Text('List_Book'));
          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),
        );
      }
    }

    publisher.dart

    class Publisher {
      final int pId;
      final String pName;
      final int? pCount;
    
      Publisher({required this.pId, required this.pName, this.pCount});
    
      factory Publisher.fromMap(Map<String, dynamic> m) =>
          Publisher(
            pId: m['p_id'],
            pName: m['p_name'],
            pCount: m['p_count'],
          );
    
      Map<String, dynamic> toMap() => {'id': pId, 'name': pName, 'count': pCount};
    }
    

    app_tabs.dart

    enum AppView { categories, publishers, books, search, add, wish }
    
    const List<AppView> tabTopViews = [
      AppView.categories,
      AppView.search,
      AppView.add,
      AppView.wish,
    ];

    widget_count_book.dart

    import 'package:book_app/core/utils/app_colors.dart';
    import 'package:flutter/material.dart';
    
    class CountBook extends StatelessWidget {
      final int? count;
      final String suffix;
      final double fontSize;
    
      const CountBook({
        super.key,
        required this.count,
        this.suffix = '冊',
        this.fontSize = 14,
      });
    
      @override
      Widget build(BuildContext context) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
          child: Text(
            '$count$suffix',
            style: TextStyle(
              color: AppColors.primaryText,
              fontSize: fontSize,
              fontWeight: FontWeight.w600,
            ),
          ),
        );
      }
    }

    widget_empty_state.dart

    import 'package:flutter/material.dart';
    
    class EmptyState extends StatelessWidget {
      final String message;
      final Widget? icon;
    
      const EmptyState({super.key, this.message = 'No data available', this.icon});
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (icon != null) icon!,
              const SizedBox(height: 8),
              Text(message),
            ],
          ),
        );
      }
    }
    

    widget_list_row.dart

    import 'package:flutter/material.dart';
    
    class ListRow extends StatelessWidget {
      final Widget? leading;
      final Widget title;
      final Widget? subtitle;
      final Widget? trailing;
      final VoidCallback? onTap;
      final EdgeInsetsGeometry contentPadding;
      final bool dense;
    
      const ListRow({
        super.key,
        this.leading,
        required this.title,
        this.subtitle,
        this.trailing,
        this.onTap,
        this.contentPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
        this.dense = true,
      });
    
      @override
      Widget build(BuildContext context) {
        return ListTile(
          leading: leading,
          title: title,
          subtitle: subtitle,
          trailing: trailing,
          onTap: onTap,
          dense: dense,
          contentPadding: contentPadding,
        );
      }
    }

    widget_loading_center.dart

    import 'package:flutter/material.dart';
    
    class LoadingCenter extends StatelessWidget {
      const LoadingCenter({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const Center(child: CircularProgressIndicator());
      }
    }

    変更

    main.dart

    import 'package:book_app/core/utils/app_colors.dart';
    import 'package:book_app/data/repositories/common.dart';
    import 'package:book_app/pages/root_page.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      
      // DB初期化処理
      await overwriteDatabaseFromAssets();
    
      runApp(const ProviderScope(child: MyApp()));
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Book_App',
          theme: ThemeData(
            primaryColor: AppColors.primaryText,
            scaffoldBackgroundColor: AppColors.background,
          ),
          home: const RootPage(),
        );
      }
    }

    list_category.dart

    import 'package:book_app/core/utils/app_colors.dart';
    import 'package:book_app/core/widgets/widget_count_book.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/category.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 ListCategoryPage extends ConsumerWidget {
      final void Function(Category) onSelectCategory;
    
      const ListCategoryPage({super.key, required this.onSelectCategory});
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final categoryAsync = ref.watch(databaseProvider);
    
        return categoryAsync.when(
          // 分類一覧取得
          data: (db) => FutureBuilder<List<Category>>(
            future: fetchCategory(db),
            builder: (context, snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
                return const LoadingCenter();
              }
              if (snapshot.hasError) {
                return Center(child: Text('Error: ${snapshot.error}'));
              }
              final categories = snapshot.data ?? [];
              if (categories.isEmpty) {
                return const EmptyState(message: 'Category not found');
              }
    
              // リスト表示
              return ListView.separated(
                itemCount: categories.length,
                separatorBuilder: (_, __) => const Divider(height: 1),
                itemBuilder: (context, index) {
                  final c = categories[index];
                  return ListRow(
                    leading: Icon(Icons.folder_sharp, color: AppColors.primaryText, size: 45),
                    title: Text('${c.cId}: ${c.cName}',
                    style: const TextStyle(color: AppColors.primaryText, fontSize: 18)),
                    trailing: CountBook(count: c.cCount),
                    onTap: () => onSelectCategory(c),
                  );
                },
              );
            },
          ),
          loading: () => const LoadingCenter(),
          error: (err, _) => Center(child: Text('Error: $err')),
        );
      }
    }

    select_repository.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();
    }

    おわり

    今回は以上となります。
    また、次回以降も見ていただけると幸いです。

     
     
    やる気も技術もあまりない、文系SEの端くれ。 書庫と防音室のある家で暮らしています。 書きたいことを書きたい時に書く日々

    あなたへのおすすめ