簡體   English   中英

在 firebaseAuth Flutter 中顯示 null 未來構建器的主屏幕

[英]Home screen showing null future builder in firebaseAuth Flutter

我目前正在嘗試從 FirebaseAuth 獲取當前用戶 state 並在用戶未注銷時在主屏幕之間切換,如果用戶已注銷則在啟動屏幕之間切換。 用戶注冊和登錄都成功並在firestore數據庫中注冊。 但是每次我從手機關閉應用程序並重新打開時,MediaQuery.of(context) 寬度都有一個 null 值並顯示錯誤。

主屏幕

但底部導航欄仍在顯示。 當我重新構建應用程序並再次登錄時它可以工作,它會將我帶到主屏幕。 它僅在我關閉並重新打開應用程序時發生。

import 'package:country_code_picker/country_localizations.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'routes.dart';
import 'package:screens/home/home_screen.dart';
import 'package:screens/splash/splash_screen.dart';

import 'constants.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      supportedLocales: [Locale('en', 'US')],
      localizationsDelegates: [CountryLocalizations.delegate],
      title: 'App',
      theme: theme(),
      routes: routes,
      home: LandingPage(),
    );
  }
}

class LandingPage extends StatelessWidget {
  const LandingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Future<FirebaseApp> _init = Firebase.initializeApp();
    return FutureBuilder(
      future: _init,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Scaffold(
            body: Center(
              child: Text("Error: ${snapshot.error}"),
            ),
          );
        }

    if (snapshot.connectionState == ConnectionState.done) {
      return StreamBuilder(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, streamSnapshot) {
          if (streamSnapshot.hasError) {
            return Scaffold(
              body: Center(
                child: Text("Error: ${streamSnapshot.error}"),
              ),
            );
          }

          if (streamSnapshot.connectionState == ConnectionState.active) {
            print(streamSnapshot.data.toString());
            if (streamSnapshot.data == null) {
              return SplashScreen();
            } else {
              return HomeScreen();
            }
          }

          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(
                backgroundColor: Colors.white,
                color: kPrimaryColor,
                strokeWidth: 3,
              ),
            ),
          );
        },
      );
    }

    return Scaffold(
      body: Center(
        child: CircularProgressIndicator(
          backgroundColor: Colors.white,
          color: kPrimaryColor,
          strokeWidth: 3,
        ),
      ),
    );
  },
);
}
}

也許我認為這是未來建造者或 stream 建造者的問題? 你們中的任何人都有這個問題的解決方案或其他方式來實現它。

Launching lib/main.dart on STK L21 in debug mode...
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:33019/yIPGCqY2gwY=/ws
I/flutter ( 4249): locale.languageCode: en
D/AwareBitmapCacher( 4249): handleInit switch not opened pid=4249
I/flutter ( 4249): User(displayName: , email: rohanbhautoo@gmail.com, emailVerified: false, isAnonymous: false, metadata: UserMetadata(creationTime: 2021-06-10 08:20:44.583, lastSignInTime: 2021-06-10 15:50:23.573), phoneNumber: , photoURL: null, providerData, [UserInfo(displayName: , email: rohanbhautoo@gmail.com, phoneNumber: , photoURL: null, providerId: password, uid: rohanbhautoo@gmail.com)], refreshToken: , tenantId: null, uid: yviaYOJ5ziayFQhvhvemB3MjkPr1)

════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building Body(dirty):
Null check operator used on a null value

The relevant error-causing widget was
Body
When the exception was thrown, this was the stack
#0      getProportionateScreenWidth
#1      Body.build
#2      StatelessElement.build
#3      ComponentElement.performRebuild
#4      Element.rebuild
...
════════════════════════════════════════════════════════════════════════════════

Size_config.dart

import 'package:flutter/material.dart';

class SizeConfig {
  static MediaQueryData? _mediaQueryData;
  static double? screenWidth;
  static double? screenHeight;
  static double? defaultSize;
  static Orientation? orientation;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData!.size.width;
    screenHeight = _mediaQueryData!.size.height;
    orientation = _mediaQueryData!.orientation;
  }
}

// Proportionate height per screen size
double getProportionateScreenHeight(double inputHeight) {
  double? screenHeight = SizeConfig.screenHeight;
  return (inputHeight / 812.0) * screenHeight!;
}

// Proportionate width per screen size
double getProportionateScreenWidth(double inputWidth) {
  double? screenWidth = SizeConfig.screenWidth;
  return (inputWidth / 375.0) * screenWidth!;
}

#0 的堆棧跟蹤行是 return (inputWidth / 375.0) * screenWidth;。 它顯示我正在使用 null 檢查 screenWidth!。

我沒有看到您實際上在哪里調用 SizeConfig().init(context)? 在項目的頂部發生之前,什么都不會為您定義。

我猜罪魁禍首是這一行:

print(streamSnapshot.data.toString());

您實際上是在下一行檢查streamSnapshot.data是否為 null:

            print(streamSnapshot.data.toString());
            if (streamSnapshot.data == null) {
              return SplashScreen();
            } else {
              return HomeScreen();
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM