带有 RiverPod 的 StreamProvider 不工作尝试从 Provider 迁移

问题描述

我试图通过将我的简单 FireStore 身份验证提供程序示例迁移到 RiverPod 来了解 RiverPod。

这是我的 AuthenticationService:

import 'package:firebase_auth/firebase_auth.dart';

class AuthenticationService {
  final FirebaseAuth _firebaseAuth;
  AuthenticationService(this._firebaseAuth);

  // with StreamProvider we listen to these changes
  Stream<User> get authStateChanges => _firebaseAuth.authStateChanges();

  Future<String> signIn({String email,String password}) async {
    try {
      await _firebaseAuth.signInWithEmailAndPassword(
          email: email,password: password);
      return 'Signed in';
    } on FirebaseAuthException catch (e) {
      return e.message;
    }
  }

  Future<String> signUp({String email,String password}) async {
    try {
      await _firebaseAuth.createUserWithEmailAndPassword(
          email: email,password: password);
      return 'Signed up ';
    } on FirebaseAuthException catch (e) {
      return e.message;
    }
  }

  Future<void> signOut() async {
    await _firebaseAuth.signOut();
  }
}

在 main.dart 中,我创建了 2 个提供者,以便我可以使用该服务并监听 AuthenticationService 内部的属性

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:meditatie_app/authentication_service.dart';
import 'package:meditatie_app/home_page.dart';
import 'package:meditatie_app/signin_page.dart';
import 'package:provider/provider.dart';

Future<void> main() async {
  // initalize Firebase and before that we need to initialize the widgets.
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // Normal provider to serve the AuthenticationService in the widgettree
        // so the login form can use this provider to use .singIn()
        Provider<AuthenticationService>(
          create: (_) => AuthenticationService(FirebaseAuth.instance),),// also a StreamProvider that serves the AuthenticationSerivce authStateChanges
        // this stream is updated by the FirebaseAuth package when users signin or out
        // this provider use context.read<AuthenticationService> to find the
        // provider dived here above
        StreamProvider(
          create: (context) =>
              context.read<AuthenticationService>().authStateChanges,)
      ],child: MaterialApp(
        title: 'Flutter Demo',theme: ThemeData(
          primarySwatch: Colors.blue,visualDensity: VisualDensity.adaptivePlatformDensity,home: AuthenticationWrapper(),);
  }
}

class AuthenticationWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User>();
    if (firebaseUser != null) {
      return HomePage();
    }
    return SignInPage();
  }
}

这里是 SingIn 页面:

import 'package:flutter/material.dart';
import 'package:meditatie_app/authentication_service.dart';
import 'package:provider/provider.dart';

class SignInPage extends StatelessWidget {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

...
          RaisedButton(
            onPressed: () {
              // Sign in code
              context.read<AuthenticationService>().signIn(
                    email: emailController.text.trim(),password: passwordController.text.trim(),);
            },...

这适用于普通的 Provider,但我无法让它与 RiverPod 一起使用

我所做的是:

我在 providers.dart 中将这些提供程序设为全局

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_riverpod/all.dart';

import 'authentication_service.dart';

final authenticationSeriviceProvider =
    Provider((ref) => AuthenticationService(FirebaseAuth.instance));
final authStateChangeProvider = StreamProvider.autoDispose<User>((ref) {
  return ref
      .watch(authenticationSeriviceProvider)
      .authStateChanges;
});

这是正确的吗? authStateChangeProvider 正在使用 authenticationServiceProvider

什么时候使用它:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:meditatie_app/home_page.dart';
import 'package:meditatie_app/signin_page.dart';
import 'package:flutter_riverpod/all.dart';
import 'providers.dart';

Future<void> main() async {
  // initialize Firebase and before that we need to initialize the widgets.
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    // riverpod needs at toplevel a Provider container
    // for storing state of different providers.
    ProviderScope(
      child: MyApp(),);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',theme: ThemeData(
        primarySwatch: Colors.blue,);
  }
}

// Riverpods ConsumerWidget
// which can consume a provider
// rebuild if the value of the provider changes
class AuthenticationWrapper extends ConsumerWidget {
  @override
  Widget build(BuildContext context,ScopedReader watch) {
    final firebaseUser = watch(authStateChangeProvider);
    if (firebaseUser != null) {
      return HomePage();
    }
    return SignInPage();
  }
}

我的“firebaseUser”不再是用户,而是 AsyncValue

当我将其更改为:

class AuthenticationWrapper extends ConsumerWidget {
  @override
  Widget build(BuildContext context,ScopedReader watch) {
    final User firebaseUser = watch(authStateChangeProvider).data?.value;
    if (firebaseUser != null) {
      return HomePage();
    }
    return SignInPage();
  }
}

它正在工作,但是我现在使用 AsyncValue 做错了什么

解决方法

扩展上一个答案 AsyncValue<T> 是一个密封类,可以将其视为 Flutter 中的 StreamBuilder 具有 AsyncSnapshot<T>,它包装了从流返回的值,并为您提供了检查其 {{1} }、connectingwaitingwithError。你的情况

withData

应该处理所有选项,现在加载时会显示进度指示器,如果有错误(连接、错误结果等)会显示 SignInPage,最后当有值时你仍然需要检查从 Stream 返回的值是否为 null(据我了解,Firebase 在没有用户登录时返回 null,这并不意味着流为空)并显示正确的小部件(如果为 null)。>

就像 Provider 一样,在检索到用户之后,您仍然需要用它来做逻辑

,

the documentation

您应该使用 AsyncValue 的公开状态来决定要呈现的内容。您的代码可能如下所示:

class AuthenticationWrapper extends ConsumerWidget {
  @override
  Widget build(BuildContext context,ScopedReader watch) {
    return watch(authStateChangeProvider).when(
      data: (user) => user == null ? SignInPage() : HomePage(),loading: () => CircularProgressIndicator(),error: (err,stack) => SignInPage(),);
  }
}

因此,将您的返回逻辑调整为您想要的数据、加载和错误状态,但这应该能让您大致了解如何使用 AsyncValue。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...