简体   繁体   English

如何使用 class Provider.of 获得 Futur function 调用的返回值?

[英]How to get the return of Futur function call with class Provider.of?

I'm building an app with flutter and I have a question about Provider.of .我正在使用 flutter 构建一个应用程序,我对Provider.of有疑问。 In my Widget I call this:在我的Widget中,我称之为:

Provider.of<Auth>(context, listen: false).signup(emailController.text, passwordController.text);

And I would like to navigate with Navigator according to the return of my signup function. I tried multiple other ways but couldn't make it work.我想根据我的signup function 的返回使用Navigator进行导航。我尝试了多种其他方法但无法使其工作。

Naively I tried this:天真地我试过这个:

onPressed: () {
  var result = Provider.of<Auth>(context, listen: false)
      .signup(emailController.text,
          passwordController.text);
  if (result == "failed") {
                              Navigator.of(context).push(MaterialPageRoute(
      builder: (ctx) => SuccessfulScreen()));
  } else {
                              Navigator.of(context).push(MaterialPageRoute(
      builder: (ctx) => UnsuccessfulScreen()));
  }
},

But I got this type for the var result : Future<String>但是我得到了这种类型的 var resultFuture<String>

Here is my tree of my project:这是我的项目树:

lib/
├── firebase_options.dart
├── images
├── main.dart
├── model
│   └── apis
│       └── auth.dart
└── view
    └── screens
        ├── login_screen.dart
        ├── signup_screen.dart
        ├── successful_screen.dart
        └── welcome_screen.dart

And the auth.dart contains this:auth.dart包含这个:

import 'package:flutter/foundation.dart';
import 'package:firebase_auth/firebase_auth.dart';

class Auth with ChangeNotifier {
  Future<String> signup(String email, String password) async {
    try {
      await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        return e.code;
      } else if (e.code == 'email-already-in-use') {
        return e.code;
      }
    } catch (e) {
      return e.toString();
    }
    return "succes";
  }

  Future<void> login(String email, String password) async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(email: email, password: password);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    }
  }
}

I could make this logic directly in my build function ( login_screen.dart ) but I found that not easy to maintain.我可以直接在我的构建 function ( login_screen.dart ) 中制作这个逻辑,但我发现这不容易维护。 So I make it difficult for me but my guess is that I'm missing something, could someone help me on this?所以我让我很难,但我猜我错过了一些东西,有人可以帮我吗?

Add the "async" keyword in the body of function and the "await" keyword before the call of your signup method, like this.在 function 的正文中添加“async”关键字,并在调用注册方法之前添加“await”关键字,如下所示。

onPressed: () async {
  var result = await Provider.of<Auth>(context, listen: false)
      .signup(emailController.text,
          passwordController.text);
  if (result == "failed") {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (_) => UnsuccessfulScreen()));
  } else {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (_) => SuccessfulScreen()));
  }
},

I often do this using callbacks:我经常使用回调来做到这一点:

class ClientManager extends ChangeNotifier {

  final FirebaseAuth auth = FirebaseAuth.instance;
 
  Client? client;

  bool _loading = false;

  bool get loading => _loading;

  set loading(bool value) {
    _loading = value;
    notifyListeners();
  }

  Future<void> signUP({
    required Client client,
    required Function(String) onFail,
    required Function() onSuccess,
  }) async {
    loading = true;
    try {
      final UserCredential result = await auth.createUserWithEmailAndPassword(
          email: client.email!, password: client.password!);

      client.id = result.user!.uid;
      this.client = client;

      await client.saveData();
      onSuccess();
      
    } on FirebaseAuthException catch (e) {
      loading = false;
      onFail(e.code);
    }

    loading = false;
  }

}
 Consumer<ClientManager>(
                          builder: (_, clientManager, __) {
                            return ElevatedButton(
                              onPressed:  clientManager.loading
                                  ? null
                                  : () {
                                    clientManager.signUP(
                                    client: client,
                                    onFail: (e) {
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        SnackBar(
                                          backgroundColor:
                                          Theme.of(context).errorColor,
                                          content: const Text(
                                              'Register'),
                                        ),
                                      );
                                    },
                                    onSuccess: () {
                                      Navigator.of(context)
                                          .pushReplacementNamed('/');
                                    },
                                  );
                                
                              },
                              child: clientManager.loading
                                  ? const SizedBox(
                                      width: 25,
                                      height: 25,
                                      child: OSCircularIndicator())
                                  : Text(AppLocalizations.of(context)!.login,
                                      style: const TextStyle(
                                          fontSize: 18,
                                          fontWeight: FontWeight.bold)),
                            );
                          }
                        ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM