LoginSignup
guabanapple
@guabanapple

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【Flutter】State変更がwatch元に反映されない

解決したいこと

Providerメソッド内部でステート更新を試みたところ、state変更は確認されたが、watchしているウィジェットに反映されない。

発生している問題・エラー

上記の通り。
なおProviderメソッド内でprint(state);したところ変更が確認されたが、ウィジェットでボタンから同様にprintしたところ、反映されていなかった。

該当するソースコード

user_model.dart
@riverpod
class UserModel extends _$UserModel {
  @override
  ImmutableUser build() => const ImmutableUser();

  static final googleSignIn = GoogleSignIn();
  final FirebaseAuth auth = FirebaseAuth.instance;

  Future<void> signIn() async {
    final GoogleSignInAccount? signInAccount = await googleSignIn.signIn();
    if (signInAccount == null) return;

    GoogleSignInAuthentication signInAuthentication =
        await signInAccount.authentication;
    final OAuthCredential credential = GoogleAuthProvider.credential(
      idToken: signInAuthentication.idToken,
      accessToken: signInAuthentication.accessToken,
    );
    User? user =
        (await FirebaseAuth.instance.signInWithCredential(credential)).user;

    if (user != null) {
      final newState = state.copyWith(
          uid: user.uid, email: user.email!, userName: user.displayName!);
      state = newState;
      print(state);  // 結果: 変更後のstate
    }
  }
}
logged_in_page.dart
class LoggedInPage extends ConsumerWidget {
  const LoggedInPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentUser = ref.watch(userModelProvider);
    final userName = currentUser.userName;
    return Scaffold(
        appBar: AppBar(
          title: const Text('LoggedIn'),
          backgroundColor: Colors.blue,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Hello $userName'),
              ElevatedButton(
                  onPressed: () async {
                    ref.read(userModelProvider.notifier).signOut();
                  },
                  child: const Text('Logout')),
              ElevatedButton(
                  onPressed: () {
                    print('state from UserPage: $currentUser');
                    // 結果:state変更前の値のまま
                  },
                  child: const Text('print state'))
            ],
          ),
        ));
  }
}
0

No Answers yet.

Your answer might help someone💌