0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】0件のときだけ EmptyView を出す

0
Posted at

個人で使用するアプリの続きです。

データが0件のときに画面が真っ白になると「通信エラーなのか、本当にデータがないのか」がユーザーに伝わらないため、次のアクションを促す UI を挟むのが目的です。

実装コード

一覧画面での分岐

build メソッドの先頭で items.isEmpty を判定し、0件なら早期リターンで EmptyView を返しています。

@override
Widget build(BuildContext context) {
  if (items.isEmpty) {
    return const EmptyView(
      title: 'プロジェクトがありません',
      message: '作成ボタンから追加してください',
      icon: Icons.assignment_outlined,
    );
  }

  return ListView.builder(
    itemCount: items.length,
    itemBuilder: (context, index) {
      final item = items[index];
      return TodoTile(
        item: item,
        onOpenDetail: () => onOpenDetail(item),
        onToggle: () => onToggle(item),
      );
    },
  );
}

共通 Widget(EmptyView)

アイコン・タイトル・メッセージを受け取る共通 Widget です。買い物リスト画面でも同じ部品を使い回し、TODO 画面では文言とアイコンだけを差し替えています。

class EmptyView extends StatelessWidget {
  final String title;
  final String message;
  final IconData icon;

  const EmptyView({
    super.key,
    this.title = 'アイテムがありません',
    this.message = '',
    this.icon = Icons.shopping_bag_outlined,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: 48,
            color: Colors.grey,
          ),
          const SizedBox(height: 16),
          Text(
            title,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Colors.grey,
            ),
          ),
          if (message.isNotEmpty) ...[
            const SizedBox(height: 8),
            Text(
              message,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ],
      ),
    );
  }
}

実装のポイント

  • デフォルト値+非null(non-nullable)で安全な設計にする
    コンストラクタに this.title = 'アイテムがありません' のようにデフォルト値を設定しているため、汎用的なリスト画面であれば const EmptyView() と書くだけでそのまま使えます。フィールドを非nullにしておくことで !(nullチェック演算子)が不要になり、message.isNotEmpty の判定だけでサブメッセージ未指定時の余計な余白も綺麗に省けます。

  • const コンストラクタでインスタンスを定数化する
    固定の文言・アイコンを渡すだけなので、呼び出し側で const EmptyView(...) と宣言できます。const を指定することで Widget を定数として扱えるため、不要なインスタンス生成を抑えられます。

まとめ
アプリ内の複数画面で「データ0件時の表示」を共通 Widget 化しておくと、余白や文字サイズの統一感が出るだけでなく、新しい一覧画面を作るときも迷わず実装できるようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?