繁体   English   中英

Flutter api 使用riverpod登录

[英]Flutter api login using riverpod

我正在尝试使用 Riverpod 通过 laravel 后端登录。 现在我只是从存储库中返回 true 或 false。 我设置了一个接受 email 和密码的表单。 isLoading变量只是为了显示一个圆形指示器。 我已经运行了代码并且它可以工作,但不确定我是否正确使用了riverpod。 有更好的方法吗?

auth_provider.dart

class Auth{
  final bool isLogin;
  Auth(this.isLogin);
}
class AuthNotifier extends StateNotifier<Auth>{
  AuthNotifier() : super(Auth(false));
  void isLogin(bool data){
    state = new Auth(data);
  }
}
final authProvider = StateNotifierProvider((ref) => new AuthNotifier());

auth_repository.dart

class AuthRepository{
  static String url = "http://10.0.2.2:8000/api/";
  final Dio _dio = Dio();
  Future<bool> login(data) async {
    try {
        Response response = await _dio.post(url+'sanctum/token',data:json.encode(data));
        return true;
    } catch (error) {
        return false;
    }
  }
}

login_screen.dart

void login() async{
  if(formKey.currentState.validate()){
    setState((){this.isLoading = true;});
    var data = {
      'email':this.email,
      'password':this.password,
      'device_name':'mobile_phone'
    };
    var result = await AuthRepository().login(data);
    if(result){
        context.read(authProvider).isLogin(true);
        setState((){this.isLoading = false;});
    }else
      setState((){this.isLoading = false;});
  }
}

由于我不是来自移动背景并且最近在我最近的项目中使用了flutter+riverpod,我不能说这是最佳实践。 但有几点我想说明:

  • 使用接口如IAuthRepository作为存储库。 Riverpod 可以充当依赖注入。
final authRepository = Provider<IAuthRepository>((ref) => AuthRepository());
  • 构建数据以发送到存储库。 如果可能,您应该将外部资源的表示、业务逻辑和显式实现分开。
  Future<bool> login(String email, String password) async {
    try {
        var data = {
          'email': email,
          'password': password,
          'device_name':'mobile_phone'
        };
        Response response = await _dio.post(url+'sanctum/token',data:json.encode(data));
        return true;
    } catch (error) {
        return false;
    }
  }
  • 不要直接从演示/屏幕调用存储库。 您可以将提供程序用于您的逻辑,它调用存储库
class AuthNotifier extends StateNotifier<Auth>{
  final ProviderReference ref;
  IAuthRepository _authRepository;

  AuthNotifier(this.ref) : super(Auth(false)) {
    _authRepository = ref.watch(authRepository);
  }

  Future<void> login(String email, String password) async {
    final loginResult = await_authRepository.login(email, password);
    state = Auth(loginResult);
  }
}

final authProvider = StateNotifierProvider((ref) => new AuthNotifier(ref));

  • 在屏幕上,您可以调用提供商的login方法
login() {
  context.read(authProvider).login(this.email, this.password);
}
  • 使用 Consumer 或 ConsumerWidget 观察 state 并决定构建什么。 它还有助于您可以创建其他一些 state,而不是使用 isLogin 进行 state 的Auth 至少,我通常会创建一个抽象的BaseAuthState ,它派生为AuthInitialStateAuthLoadingStateAuthLoginStateAuthErrorState等。
class AuthNotifier extends StateNotifier<BaseAuthState>{
  ...
  AuthNotifier(this.ref) : super(AuthInitialState()) { ... }
  ...
}
Consumer(builder: (context, watch, child) {
  final state = watch(authProvider.state);
  if (state is AuthLoginState) ...
  else if (state is AuthLoadingState) ...
  ...
})

我喜欢使用枚举或 class 来验证 state 而不是使用布尔值

enum AuthState { initialize, authenticated, unauthenticated }

并用于登录 state

enum LoginStatus { initialize, loading, success, failed }

暂无
暂无

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

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