

下記の画面にログイン済みの場合はログイン後の画面(signed_in_screen)、ログインしていない場合はログイン前の画面(community
_screen)の画面を実装したいのですがコーディングを教えてください。

kaisupo/screens/community_screen.dart

[code]

    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:kaisupo/screens/signed_in_screen.dart';
    import 'package:flutter/material.dart';
    import 'package:kaisupo/parts/back_gradation_setting.dart';
    import 'package:kaisupo/parts/bottom_navigation_bar.dart';
    import 'package:kaisupo/parts/title_text.dart';
    
    class CommunityScreen extends StatefulWidget {
      @override
      _CommunityScreenState createState() => _CommunityScreenState();
    }
    
    class _CommunityScreenState extends State<CommunityScreen> {
      //現在のタブを保持する変数の定義と初期値の設定
      var _currentTab = TabItem.community;
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
      final TextEditingController _emailController = TextEditingController();
      final TextEditingController _passwordController = TextEditingController();
    
      //タブの更新
      void _selectedTab(TabItem tabItem) {
        setState(() => _currentTab = tabItem);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: PreferredSize(
            preferredSize: const Size.fromHeight(60.0),
            child: AppBar(
              title: TitleTextCreate(
                  title: "***",
                  size: 30,
                  color: Colors.white,
                  radius: 18,
                  shadow: Colors.indigo),
              centerTitle: true,
              backgroundColor: Colors.lightGreen.shade400,
            ),
          ),
          //BottomNavigationBarセット
          bottomNavigationBar: BottomNavigationBarSet(
            currentTab: _currentTab,
            onSelectedTab: _selectedTab,
          ),
          body: Form(
            key: _formKey,
            child: Stack(children: [
              //背景グラデーション
              BackGroundDecoration(
                  first: Colors.deepOrangeAccent.shade200,
                  second: Colors.amber.shade300,
                  third: Colors.yellow.shade200),
              Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                TextFormField(
                  controller: _emailController,
                  decoration: InputDecoration(labelText: 'メールアドレス'),
                  keyboardType: TextInputType.emailAddress,
                  validator: (String? value) {
                    if (value?.isEmpty == true) {
                      return 'メールアドレスを入力して下さい';
                    }
                    return null;
                  },
                ),
                SizedBox(height: 8),
                TextFormField(
                  controller: _passwordController,
                  decoration: InputDecoration(labelText: 'パスワード'),
                  keyboardType: TextInputType.visiblePassword,
                  obscureText: true,
                  validator: (String? value) {
                    if (value?.isEmpty == true) {
                      return 'パスワードを入力して下さい';
                    }
                    return null;
                  },
                ),
                SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () => _onSignIn(),
                    child: Text('ログイン'),
                  ),
                ),
                SizedBox(height: 8),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () => _onSignUp(),
                    child: Text('新規登録'),
                  ),
                ),
              ]),
            ]),
          ),
        );
      }
    
      Future<void> _onSignIn() async {
        try {
          if (_formKey.currentState?.validate() != true) {
            return;
          }
    
          //新規登録と同じく入力された内容をもとにログイン処理を行う
          final String email = _emailController.text;
          final String password = _passwordController.text;
          await FirebaseAuth.instance
              .signInWithEmailAndPassword(email: email, password: password);
    
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (_) => SignedInScreen(),
            ),
          );
        } catch (e) {
          await showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text('エラー'),
                content: Text(e.toString()),
              );
            },
          );
        }
      }
    
      Future<void> _onSignUp() async {
        try {
          if (_formKey.currentState?.validate() != true) {
            return;
          }
          final String email = _emailController.text;
          final String password = _passwordController.text;
          await FirebaseAuth.instance
              .createUserWithEmailAndPassword(email: email, password: password);
    
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (_) => SignedInScreen(),
            ),
          );
        } catch (e) {
          await showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text('エラー'),
                content: Text(e.toString()),
              );
            },
          );
        }
      }
    }
    
[/code]

kaisupo/screens/signed_in_screen.dart

[code]

    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter/material.dart';
    import 'package:kaisupo/screens/community_screen.dart';
    import 'package:kaisupo/parts/back_gradation_setting.dart';
    import 'package:kaisupo/parts/bottom_navigation_bar.dart';
    import 'package:kaisupo/parts/title_text.dart';
    
    class SignedInScreen extends StatefulWidget {
      @override
      _SignedInScreenState createState() => _SignedInScreenState();
    }
    
    class _SignedInScreenState extends State<SignedInScreen> {
      var _currentTab = TabItem.community;
      //タブの更新
      void _selectedTab(TabItem tabItem) {
        setState(() => _currentTab = tabItem);
      }
    
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: PreferredSize(
            preferredSize: const Size.fromHeight(60.0),
            child: AppBar(
              title: TitleTextCreate(
                  title: "***",
                  size: 30,
                  color: Colors.white,
                  radius: 18,
                  shadow: Colors.indigo),
              centerTitle: true,
              backgroundColor: Colors.lightGreen.shade400,
              actions: [
                //ログアウト用ボタン
                IconButton(
                  onPressed: () => _onSignOut(),
                  icon: Icon(Icons.exit_to_app),
                ),
              ],
            ),
          ),
          //BottomNavigationBarセット
          bottomNavigationBar: BottomNavigationBarSet(
            currentTab: _currentTab,
            onSelectedTab: _selectedTab,
          ),
        );
      }
    
      Future<void> _onSignOut() async {
        //ログアウト処理
        await FirebaseAuth.instance.signOut();
    
        //ログアウトに成功したらログイン画面に戻す
        //現在の画面は不要になるのでpushReplacementを使う
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (_) => CommunityScreen(),
          ),
        );
      }
    }
    
[/code]


CC BY-SA 4.0
2023-01-30T01:48:21.293
93613
2023-01-30T05:28:16.793
2023-01-30T05:28:16.793
56819
56819
question
firebase flutter
firebase_authでのログイン状態の維持、ページ遷移