我已经 "null check opreator used on a null value"
i've been getting "null check opreator used on a null value"
我一直收到错误“null chack opreator used on a null value”
每当我尝试使用提供程序从我的 firestore 数据库中提取值并更改通知程序时
这是我的 user_provider.dart
import 'package:flutter/widgets.dart';
import 'package:test_app/models/user.dart';
import 'package:test_app/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
这是我的 home.dart 我从 firestore 中提取数据的地方
import 'package:bottom_navy_bar/bottom_navy_bar.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/components/background.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/models/user.dart' as model;
// import 'dart:html';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
@override
Widget build(BuildContext context) {
model.User? user = Provider.of<UserProvider>(context).getUser;
return Scaffold(body: Text(user.email),);
}
}
这是我的 main.dart incase
import 'dart:ffi';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/pages/home.dart';
import 'package:test_app/pages/login.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:test_app/pages/signup.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/utilis/routes.dart';
void main() async {
// ignore: prefer_const_constructors
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => UserProvider(),
)
],
child: MaterialApp(
// home: Home(),
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
darkTheme: ThemeData(brightness: Brightness.light),
theme: ThemeData(
primarySwatch: Colors.deepPurple,
fontFamily: GoogleFonts.mcLaren().fontFamily,
appBarTheme: AppBarTheme(
color: Colors.white,
elevation: 0.0,
iconTheme: IconThemeData(color: Colors.black),
)),
// ignore: prefer_const_constructors
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// Checking if the snapshot has any data or not
if (snapshot.hasData) {
// if snapshot has data which means user is logged in then we check the width of screen and accordingly display the screen layout
return const Home();
} else if (snapshot.hasError) {
return const Login();
}
}
// means connection to future hasnt been made yet
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const Login();
})),
);
}
}
我的调试控制台
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building Home(dirty, dependencies:
[_InheritedProviderScope<UserProvider?>], state: _HomeState#17895):
Null check operator used on a null value
The relevant error-causing widget was:
Home Home:file:///C:/Users/abc/Desktop/flutter/test_app/lib/main.dart:53:34
When the exception was thrown, this was the stack:
#0 UserProvider.getUser (package:test_app/providers/user_provider.dart:9:28)
#1 _HomeState.build (package:test_app/pages/home.dart:36:59)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4870:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4919:11)
#8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
#9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#10 Element.updateChild (package:flutter/src/widgets/framework.dart:3524:20)
#11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4780:16)
#12 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#13 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#15 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#16 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#17 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#18 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#19 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:862:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
我的应用程序运行正常,但在打开之前它显示了一个红屏,其中错误空检查运算符用于空值,一秒钟后它熄灭并继续工作,但调试在调试控制台中显示以下错误
你应该写User get getUser => _user ?? User();
而不是User get getUser => _user!;
在my user_provider.dart
或者你可以这样写User _user = User();
而不是User? _user;
我一直收到错误“null chack opreator used on a null value” 每当我尝试使用提供程序从我的 firestore 数据库中提取值并更改通知程序时
这是我的 user_provider.dart
import 'package:flutter/widgets.dart';
import 'package:test_app/models/user.dart';
import 'package:test_app/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
这是我的 home.dart 我从 firestore 中提取数据的地方
import 'package:bottom_navy_bar/bottom_navy_bar.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/components/background.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/models/user.dart' as model;
// import 'dart:html';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
@override
Widget build(BuildContext context) {
model.User? user = Provider.of<UserProvider>(context).getUser;
return Scaffold(body: Text(user.email),);
}
}
这是我的 main.dart incase
import 'dart:ffi';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/pages/home.dart';
import 'package:test_app/pages/login.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:test_app/pages/signup.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/utilis/routes.dart';
void main() async {
// ignore: prefer_const_constructors
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => UserProvider(),
)
],
child: MaterialApp(
// home: Home(),
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
darkTheme: ThemeData(brightness: Brightness.light),
theme: ThemeData(
primarySwatch: Colors.deepPurple,
fontFamily: GoogleFonts.mcLaren().fontFamily,
appBarTheme: AppBarTheme(
color: Colors.white,
elevation: 0.0,
iconTheme: IconThemeData(color: Colors.black),
)),
// ignore: prefer_const_constructors
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// Checking if the snapshot has any data or not
if (snapshot.hasData) {
// if snapshot has data which means user is logged in then we check the width of screen and accordingly display the screen layout
return const Home();
} else if (snapshot.hasError) {
return const Login();
}
}
// means connection to future hasnt been made yet
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const Login();
})),
);
}
}
我的调试控制台
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building Home(dirty, dependencies:
[_InheritedProviderScope<UserProvider?>], state: _HomeState#17895):
Null check operator used on a null value
The relevant error-causing widget was:
Home Home:file:///C:/Users/abc/Desktop/flutter/test_app/lib/main.dart:53:34
When the exception was thrown, this was the stack:
#0 UserProvider.getUser (package:test_app/providers/user_provider.dart:9:28)
#1 _HomeState.build (package:test_app/pages/home.dart:36:59)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4870:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4919:11)
#8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
#9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#10 Element.updateChild (package:flutter/src/widgets/framework.dart:3524:20)
#11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4780:16)
#12 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#13 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#15 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#16 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#17 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#18 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#19 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:862:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
我的应用程序运行正常,但在打开之前它显示了一个红屏,其中错误空检查运算符用于空值,一秒钟后它熄灭并继续工作,但调试在调试控制台中显示以下错误
你应该写User get getUser => _user ?? User();
而不是User get getUser => _user!;
在my user_provider.dart
或者你可以这样写User _user = User();
而不是User? _user;