Firebase 注销后 Flutter 应用程序崩溃

Kil*_*ian 5 firebase firebase-authentication flutter riverpod

我对 Flutter 还是很陌生。我正在将 Riverpod 与 Firebase 一起使用,并在尝试注销后出现崩溃。如果有人可以提供帮助,那就太棒了!如果这只是一个菜鸟错误,我已经很抱歉了:D

我的 main.dart 看起来像这样:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(ProviderScope(child: App()));
}

class App extends StatelessWidget {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire
      future: _initialization,
      builder: (context, snapshot) {
        // Check for Errors
        if (snapshot.hasError) {
          return Center(child: Text("Error"));
        }

        // Once complete, show application
        if (snapshot.connectionState == ConnectionState.done) {
          return MaterialApp(
            home: MyApp(),
            darkTheme: ThemeData.dark(),
          );
        }

        // Otherwise, show loadin while waiting for init to complete
        return LoadingScreen();
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个简短的 app.dart 文件。

class MyApp extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final userAsyncValue = watch(authStateChangesProvider);

    return userAsyncValue.when(
        data: (user) {
          if (user == null) {
            return LoginScreen();
          } else {
            return HomeScreen();
          }
        },
        loading: () => CircularProgressIndicator(),
        error: (_, __) => Container());
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个提供者文件

final firebaseAuthProvider = Provider<FirebaseAuth>((ref) => FirebaseAuth.instance);

final authStateChangesProvider = StreamProvider<User?>((ref) => ref.watch(firebaseAuthProvider).authStateChanges());
Run Code Online (Sandbox Code Playgroud)

和一个 AuthService 文件:

class AuthenticationService {
  final _auth = FirebaseAuth.instance;

  Future logInWithEmailAndPassword(email, password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }

  Future logOut() async {
    await _auth.signOut();
  }
}
Run Code Online (Sandbox Code Playgroud)

最后我的登录页面看起来像这样

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();
    final _inputService = InputService();
    final _emailcontroller = TextEditingController();
    final _passwordcontroller = TextEditingController();
    final _auth = AuthenticationService();

    return Form(
      key: _formKey,
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              TextFormField(
                  decoration: InputDecoration(hintText: "Email", hintStyle: TextStyle(color: Colors.white)),
                  controller: _emailcontroller,
                  style: TextStyle(color: Colors.white),
                  keyboardType: TextInputType.emailAddress,
                  validator: (value) => _inputService.isInputValid(value, "email")),
              TextFormField(
                decoration: InputDecoration(hintText: "Password", hintStyle: TextStyle(color: Colors.white)),
                obscureText: true,
                controller: _passwordcontroller,
                style: TextStyle(color: Colors.white),
                validator: (value) => _inputService.isInputValid(value, "password"),
              ),
              ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      _auth.logInWithEmailAndPassword(_emailcontroller.text, _passwordcontroller.text);
                    }
                  },
                  child: Text(
                    "Login",
                    style: TextStyle(
                      fontSize: 20,
                    ),
                  )),
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

和一个真正简单的主屏幕

class HomeScreen extends StatelessWidget {
  final _auth = AuthenticationService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.black,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: () {
                  _auth.logOut();
                },
                child: Text(
                  "Logout",
                  style: TextStyle(color: Colors.white),
                ))
          ],
        ));
  }
}
Run Code Online (Sandbox Code Playgroud)

登录就像一个魅力,但一旦我注销应用程序崩溃,我刚刚退出(sigterm),如果你告诉我如何在 vscode 中找到更多调试信息,我很乐意提供它:D

此外,它实际上似乎正确地将我从 Firebase 注销,至少在模拟器上重新打开应用程序时,我回到了登录屏幕。所以我猜它与 MyApp 类中的 ConsumerWidget 的身份验证状态更改和重建有关吗?

如果有人可以提供帮助,那就太棒了!如果你认为我的代码很糟糕,那么很高兴纠正我,我只是想把我在教程中找到的东西放在一起,并且总是很高兴被纠正:D

编辑:

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_core: "^1.0.1"
  firebase_auth: "^1.0.1"
  flutter_riverpod: "^0.13.1+1"
Run Code Online (Sandbox Code Playgroud)