flutter应用程序,未处理的异常:在Null值上使用了Null检查运算符



这是一个简单的flutter应用程序。我在连接firebase的注册页面上收到了这个错误。当我尝试注册时,它仍然在思考⭕正在旋转,我在调试控制台中收到以下错误:

VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value
#0      _SignupScreenState.signUpUser package:instagram_flutter/screens/signup_screen.dart:5

有什么想法吗?

这是我认为问题来源的代码:

(_image != null
? CircleAvatar

这就是代码块:

Stack(
children: [
_image != null
? CircleAvatar(
radius: 32,
backgroundImage: MemoryImage(_image!),
backgroundColor: Colors.red,
)
: const CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
),

我刚开始编码和颤动,我应该用什么来代替">

以下是sign_up_screen的完整代码(取自教程(:

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_flutter/resources/auth_methods.dart';
import 'package:instagram_flutter/responsive/mobile_screen_layout.dart';
import 'package:instagram_flutter/responsive/web_screen_layout.dart';
import 'package:instagram_flutter/screens/login_screen.dart';
import 'package:instagram_flutter/utils/colors.dart';
import 'package:instagram_flutter/utils/utils.dart';
import '../responsive/responsive_layout_screen.dart';
import '../widgets/text_field_input.dart';
class SignupScreen extends StatefulWidget {
const SignupScreen({Key? key}) : super(key: key);
@override
_SignupScreenState createState() => _SignupScreenState();
}
class _SignupScreenState extends State<SignupScreen> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _bioController = TextEditingController();
bool _isLoading = false;
Uint8List? _image;
@override
void dispose() {
super.dispose();
_emailController.dispose();
_passwordController.dispose();
_usernameController.dispose();
}
void signUpUser() async {
// set loading to true
setState(() {
_isLoading = true;
});
// signup user using our authmethodds
String res = await AuthMethods().signUpUser(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
bio: _bioController.text,
file: _image!);
// if string returned is sucess, user has been created
if (res == "success") {
setState(() {
_isLoading = false;
});
// navigate to the home screen
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const ResponsiveLayout(
mobileScreenLayout: MobileScreenLayout(),
webScreenLayout: WebScreenLayout(),
),
),
);
} else {
setState(() {
_isLoading = false;
});
// show the error
showSnackBar(context, res);
}
}
selectImage() async {
Uint8List im = await pickImage(ImageSource.gallery);
// set state because we need to display the image we selected on the circle avatar
setState(() {
_image = im;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 32),
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
child: Container(),
flex: 2,
),
SvgPicture.asset(
'assets/ic_instagram.svg',
color: primaryColor,
height: 64,
),
const SizedBox(
height: 64,
),
Stack(
children: [
_image != null
? CircleAvatar(
radius: 64,
backgroundImage: MemoryImage(_image!),
backgroundColor: Colors.red,
)
: const CircleAvatar(
radius: 64,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
),
Positioned(
bottom: -10,
left: 80,
child: IconButton(
onPressed: selectImage,
icon: const Icon(Icons.add_a_photo),
),
)
],
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your username',
textInputType: TextInputType.text,
textEditingController: _usernameController,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your email',
textInputType: TextInputType.emailAddress,
textEditingController: _emailController,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your password',
textInputType: TextInputType.text,
textEditingController: _passwordController,
isPass: true,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your bio',
textInputType: TextInputType.text,
textEditingController: _bioController,
),
const SizedBox(
height: 24,
),
InkWell(
child: Container(
child: !_isLoading
? const Text(
'Sign up',
)
: const CircularProgressIndicator(
color: primaryColor,
),
width: double.infinity,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: const ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
),
color: blueColor,
),
),
onTap: signUpUser,
),
const SizedBox(
height: 12,
),
Flexible(
child: Container(),
flex: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: const Text(
'Already have an account?',
),
padding: const EdgeInsets.symmetric(vertical: 8),
),
GestureDetector(
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LoginScreen(),
),
),
child: Container(
child: const Text(
' Login.',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
padding: const EdgeInsets.symmetric(vertical: 8),
),
),
],
),
],
),
),
),
);
}
}

还有auth页面,其中包括关于的警告

file != null) {:

警告说:

The operand can't be null, so the condition is always true.
Remove the condition.dartunnecessary_null_comparison

auth_methods.dart:

import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:instagram_flutter/resources/storage_methods.dart';
class AuthMethods {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
//sign up user
Future<String> signUpUser({
required String email,
required String password,
required String username,
required String bio,
required Uint8List file,
}) async {
String res = "Some error Occurred";
try {
if (email.isNotEmpty ||
password.isNotEmpty ||
username.isNotEmpty ||
bio.isNotEmpty ||
file != null) {
// registering user in auth with email and password
UserCredential cred = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
String photoUrl = await StorageMethods()
.uploadImageToStorage('profilePics', file, false);
await _firestore.collection('users').doc(cred.user!.uid).set({
'username': username,
'uid': cred.user!.uid,
'email': email,
'bio': bio,
'followers': [],
'following': [],
'photoUrl': photoUrl,
});
res = "success";
} else {
res = "Please enter all the fields";
}
} catch (err) {
return err.toString();
}
return res;
}
// logging in user
Future<String> loginUser({
required String email,
required String password,
}) async {
String res = "Some error Occurred";
try {
if (email.isNotEmpty || password.isNotEmpty) {
// logging in user with email and password
await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
res = "success";
} else {
res = "Please enter all the fields";
}
} catch (err) {
return err.toString();
}
return res;
}
Future<void> signOut() async {
await _auth.signOut();
}
}

确保_image的声明类型为MemoryImage,如下所示:MemoryImage? _image;然后,在使用背景图像的值时,只使用_image,而不是MemoryImage(_image!)

尝试使用这种方式。。

Stack(
children: [
_image == null
? const CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
):
CircleAvatar(
radius: 32,
backgroundImage: MemoryImage(_image),
backgroundColor: Colors.red,
),

signUpUser上,您直接使用bang!而不检查null。

此处

// signup user using our authmethodds
...
file: _image!);

尝试

void signUpUser() async {
if (_image == null) {
debugPrint("got null on _image");
_isLoading = false;
return;
}

Stack上的一切似乎都很好

相关内容

  • 没有找到相关文章

最新更新