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?

ログイン済みのユーザが利用できる画面に未ログインユーザがアクセスする場合

Posted at

🧠 1. ログイン状態 Provider

provider

final authProvider = StateProvider<bool>((ref) => false); // false = 未ログイン

🧩 2. ログイン必須画面ラッパー

LoginRequiredScreen.dart
class LoginRequiredScreen extends ConsumerWidget {
  final Widget child;

  const LoginRequiredScreen({super.key, required this.child});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isLoggedIn = ref.watch(authProvider);

    if (!isLoggedIn) {
      return const LoginPromptScreen(); // ログイン案内画面へ
    }

    return child; // ログイン済みなら本来の画面を表示
  }
}

🖥️ 3. ログイン案内画面 LoginPromptScreen

LoginPromptScreen.dart

class LoginPromptScreen extends StatelessWidget {
  const LoginPromptScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("ログインが必要です")),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text("この画面を表示するにはログインが必要です。"),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const LoginScreen()),
                );
              },
              child: const Text("ログインする"),
            ),
          ],
        ),
      ),
    );
  }
}

🧪 4. Chatroom や History 画面での使い方

chatroom_screen.dart

class ChatroomScreen extends StatelessWidget {
  const ChatroomScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return LoginRequiredScreen(
      child: Scaffold(
        appBar: AppBar(title: const Text("チャットルーム")),
        body: const Center(child: Text("ここにチャット内容が表示されます")),
      ),
    );
  }
}

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?