Почему FutureProvider дважды возвращает результат при нажатии и возвращает AsyncLoading, но не AsyncValue?

Я уже подтвердил, что определенный пользователь (с адресом электронной почты и паролем) зарегистрирован в Firebase Authentication, и я попытаюсь проверить, работают ли ошибки try-catch, когда пользователи публикуют повторяющийся адрес электронной почты, соответственно написал коды следующим образом:

Я ожидаю с первого нажатия следующим образом:

  1. будет напечатано на консоли в//here2
  2. и должен быть возвращен в
  3. и, наконец, пользователь может оставаться какnavigatorAnimation()не работает и только что вернулся в//here4

Однако на самом деле он работает с первым нажатием следующим образом:

  1. successпечатается на консоли в//here1
  2. и возвращается в
  3. печатается на консоли в

Я не мог понять, почему эти вещи происходят с первым нажатием, особенно,(try)successи(catch)failвыполняются одновременно. И я не мог найти много оAsyncLoading<bool>()в официальном документе revier_pod.

Кроме того, я попробовал второе касание и обнаружил, что оно вернулосьAsyncData<bool>(value: false)как и ожидалось, ноfailне был напечатан на консоли в//here3.

Я, наконец, не смог решить эту любопытную проблему самостоятельно, и, пожалуйста, сообщите мне, в чем проблема и как я могу ее исправить, как я ожидал.

      //auth.dart
import 'package:firebase_auth/firebase_auth.dart';

Future<bool> authUser(ref) async {
        try {
          print("success");//here1
          final FirebaseAuth auth = FirebaseAuth.instance;
          final UserCredential _result =
            await auth.createUserWithEmailAndPassword(
            email: emailController.text,
            password: maskController.text,
          );
           User _user = _result.user!; 
           _user.sendEmailVerification();
           return true;
        } on FirebaseAuthException catch (e) {
          print("fail");//here2
          if (e.code == 'email-already-in-use') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ01',color: MyStyle.alertColor));
          } else if (e.code == 'invalid-email') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ02',color: MyStyle.alertColor));
          } else if (e.code == 'operation-not-allowed') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ03',color: MyStyle.alertColor)); 
          } else if (e.code == 'weak-password') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ04',color: MyStyle.alertColor)); 
          } else if (e.code == 'network-request-failed') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ05',color: MyStyle.alertColor)); 
          } else if (e.code == 'too-many-requests') {
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ06',color: MyStyle.alertColor)); 
          }else{
            ref.read(completeErrorMessage.notifier).update((state) => awesomeText(icon: FontAwesomeIcons.lightbulb, text: 'EZ10',color: MyStyle.alertColor)); 
          }
          return false;
        }
}
      //navigator.dart
import 'dart:developer';
import 'dart:ui';
import 'package:cards/control/auth.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final authFutureProvider = FutureProvider<bool>(
  (ref) async => authUser(ref),
);

class MyNavigator extends ConsumerWidget {
  final Widget destinationTo;
  final BuildContext context;
  final String goBack;
  final List<GlobalKey<FormState>>? formKeyList;

  MyNavigator(
      {required this.destinationTo,
      required this.context,
      required this.goBack,
      this.formKeyList,
      Key? key,
      required})
      : super(key: key) {
    // print(destinationTo.runtimeType);
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // }
    return TextButton(
      style: TextButton.styleFrom(
        foregroundColor: MyStyle.mainColor,
      ),
      onPressed: () {
        switch (goBack) {
          case "XX":
           //omitted
          break;
          case "YY":
            //omitted
          break;

          case "sendEmail":
            ref.read(sendEmailPressProvider.notifier).update((state) => true);
            if (ref.watch(sendEmailPressProvider)) {
              final authC = ref.watch(authFutureProvider);
              print(authC);//here3
              authC.when(
                data: (data) {
                  if (data == true) {
                    navigatorAnimation(
                        context: context,
                        goBack: goBack,
                        destinationTo: destinationTo);
                  } else {
                    return;//here 4
                  }
                },
                error: (error, stackTrace) => print(error),
                loading: () => null,
              );
            }
            break;
        }
      },
      child: Text(goBack),
    );
  }
}

void navigatorAnimation(
    {required BuildContext context,
    required String goBack,
    required Widget destinationTo}) {
  Offset? begin;
  Navigator.of(context).push(
    PageRouteBuilder(
      pageBuilder: (context, animation, secondaryAnimation) {
        return destinationTo;
      },
      transitionDuration: const Duration(milliseconds: 300),
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        goBack == "XX" ? begin = const Offset(1.0, 0.0) : 0;
        goBack == "YY" ? begin = const Offset(-1.0, 0.0) : 0;
        goBack == "sendEmail" ? begin = const Offset(1.0, 0.0) : 0;
        const Offset end = Offset.zero;
        final Animatable<Offset> tween = Tween(begin: begin, end: end)
            .chain(CurveTween(curve: Curves.easeInOut));
        final Animation<Offset> offsetAnimation = animation.drive(tween);
        return SlideTransition(
          position: offsetAnimation,
          child: child,
        );
      },
    ),
  );
}

0 ответов

Другие вопросы по тегам