<asynchronous suspension> 使用 firebase WidgetsFlutterBinding.ensureInitialized(); 后等待 Firebase.initializeApp();

问题描述 投票:0回答:1

我正在做 Angela Yu 的 flutter 课程,它非常过时,所以我不断遇到这样的问题。我正在尝试将 Firebase 集成到聊天应用程序中,但由于某种原因,我现在不断发现我已经实现了 Firebase.initializeApp()。我有点不明白为什么会这样。我尝试清理我的 pubspec 文件但无济于事。我已在问题底部附上了我遇到的错误。

任何帮助将不胜感激。

这是我的主要文件

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/screens/welcome_screen.dart';
import 'package:flash_chat/screens/login_screen.dart';
import 'package:flash_chat/screens/registration_screen.dart';
import 'package:flash_chat/screens/chat_screen.dart';

Future<void> main() async {
  //Why we need the below code
  // 1. https://stackoverflow.com/questions/63492211/no-firebase-app-default-has-been-created-call-firebase-initializeapp-in
  // 2. https://stackoverflow.com/questions/63873338/what-does-widgetsflutterbinding-ensureinitialized-do
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    FlashChat(),
  );
}

class FlashChat extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // theme: ThemeData.dark().copyWith(
      //     // textTheme: TextTheme(
      //     //   bodyLarge: TextStyle(color: Colors.black54),
      //     // ),
      //     ),
      home: WelcomeScreen(),
      //You cant use the home property if your going to use initial routes as they will conflict with each other
      initialRoute: WelcomeScreen.id,
      //Use this to only write the string once within the welcome screen as a property to avoid errors.
      //Without the word static it brings back a new object, with static is just attached to the class
      routes: {
        //This is a map
        WelcomeScreen.id: (context) => WelcomeScreen(),
        LoginScreen.id: (context) => LoginScreen(),
        RegistrationScreen.id: (context) => RegistrationScreen(),
        ChatScreen.id: (context) => ChatScreen(),
      },
    );
  }
}

如果需要的话,这是我的注册和聊天屏幕。我添加它是因为它有一些 Firebase 功能,但我认为它们甚至没有机会被使用

import 'package:flash_chat/constants.dart';
import 'package:flash_chat/screens/chat_screen.dart';
import 'package:flash_chat/screens/welcome_screen.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/components/rounded_button.dart';
import 'package:firebase_auth/firebase_auth.dart';

class RegistrationScreen extends StatefulWidget {
  static const String id = 'registration_screen';
  @override
  _RegistrationScreenState createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  //create a new auth instance inside registration screen state, make it private so other classes cant use it.
  final _auth = FirebaseAuth.instance;
  //Create variables to store email and password from the text fields
  late String email;
  late String password;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Hero(
              tag: 'logo',
              child: Container(
                height: 200.0,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      Navigator.pushNamed(context, WelcomeScreen.id);
                    });
                  },
                  child: Image.asset(
                    'images/logo.png',
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 48.0,
            ),
            TextField(
              keyboardType: TextInputType.emailAddress,
              textAlign: TextAlign.center,
              onChanged: (value) {
                //Do something with the user input.
                email = value;
              },
              decoration: kTextFieldDecoration.copyWith(
                hintText: 'Enter your email',
              ),
            ),
            SizedBox(
              height: 8.0,
            ),
            TextField(
              obscureText: true,
              textAlign: TextAlign.center,
              onChanged: (value) {
                //Do something with the user input.
                password = value;
              },
              decoration: kTextFieldDecoration.copyWith(
                hintText: 'Enter your password',
              ),
            ),
            SizedBox(
              height: 24.0,
            ),
            RoundedButton(
                colour: Colors.blueAccent,
                pressHandler: () async {
                  //Implement registration capability
                  print(email);
                  print(password);
                  try {
                    final newUser = await _auth.createUserWithEmailAndPassword(
                        email: email, password: password);
                    if (newUser != null) {
                      Navigator.pushNamed(context, ChatScreen.id);
                    }
                  } catch (e) {
                    print(e);
                  }
                },
                title: 'Register')
          ],
        ),
      ),
    );
  }
}

聊天画面

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';

class ChatScreen extends StatefulWidget {
  static const String id = 'chat_screen';
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final _auth = FirebaseAuth.instance;
  //User replaces FirebaseUser and takes the current logged in users details from firebase and stores them in logged in user.
  late User loggedInUser;

  //trigger the getCurrentUser() function/method
  @override
  void initState() {
    super.initState();
    //call get current user
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        //Check logged in user variable is working correctly;
        print(loggedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                //Implement logout functionality
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      onChanged: (value) {
                        //Do something with the user input.
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      //Implement send functionality.
                    },
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

这是我在运行部分收到的错误消息

Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app-debug.apk...
Debug service listening on ws://127.0.0.1:63336/nNuBI5A9VV8=/ws
Syncing files to device sdk gphone64 x86 64...
E/flutter ( 8270): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(null-error, Host platform returned null value for non-null return value., null, null)
E/flutter ( 8270): #0      FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:248:7)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #1      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89:25)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #2      Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:31)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #3      main (package:flash_chat/main.dart:13:3)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): 

database flutter firebase asynchronous firebase-authentication
1个回答
0
投票

您需要提供

options
.initializeApp
,它将由
firebase init
cli 生成。你可以检出lib中的
firebase_options.dart
文件然后使用它。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

}

更多关于颤振/设置

© www.soinside.com 2019 - 2024. All rights reserved.