Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null check operator used on a null value from userProvider #12

Open
javaskrskr opened this issue Jul 23, 2022 · 38 comments
Open

Null check operator used on a null value from userProvider #12

javaskrskr opened this issue Jul 23, 2022 · 38 comments
Labels
waiting Waiting for Response

Comments

@javaskrskr
Copy link

Hello everyone, I am encountering the issue of null check, I followed the tutorial video, around 3:17:28, when I switched the networkImage with user.photoUrl:
image

The null check error was thrown from the userProvider, error message: Exception has occurred. _CastError (Null check operator used on a null value), my code of userProvider.dart:
image

I have already tried upgrading the pub version, or using the final Userprovider userprovider instead of User, the result is either showing nothing after pressing the upload icon, or throwing the error of: Exception has occurred. _CastError (Null check operator used on a null value).

I would like to know how to resolve it, Thanks!

@lomanu4
Copy link

lomanu4 commented Aug 2, 2022

you have solved it, if not, I'll tell you

@javaskrskr
Copy link
Author

you have solved it, if not, I'll tell you

Hello, I have not yet solving it, may I know the possible solutions?

@lomanu4
Copy link

lomanu4 commented Aug 2, 2022

add this in mobile screen
//model.User? user = Provider.of(context).getUser;

Text('${user!.email ?? null }')

in ResponsiveLayout check

@OverRide
void initState() {

super.initState();
addData();

}
addData()async {
UserProvider _userProvider = Provider.of(context,listen: false);
await _userProvider.refreshUser();
}

@bozhen-ahmed964
Copy link

can you be more specific please cos i have same issue
add this in mobile screen
//model.User? user = Provider.of(context).getUser;

Text('${user!.email ?? null }')

in where do you mean to add this line

@kerumy
Copy link

kerumy commented Sep 13, 2022

@bozhen-ahmed964

In my case, this code works for me.

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

model.User? user = Provider.of(context).getUser;
final isUserLogin = user?.username ?? false;
~
body: isUserLogin == false
? const Text('No User')
: Center(child: Text(user!.username))
~

@bozhen-ahmed964
Copy link

I would give it a try some of my friends told me that somethings wrong with the user model

@jammydman
Copy link

I am also struggling with the same error and can't see how to implement this code. Could you please show where in the code these lines should be added? Thank you

@jinosh05
Copy link

Hello there, the error was due to null-safety. Just remove the nullability in User? and add late keyword. Check my fork for more details

@jammydman
Copy link

jammydman commented Sep 24, 2022

Thank you for your response, this fixed some of the issue. I am now getting a new error:

Exception caught by widgets library ═══════════════════════════════════
LateInitializationError: Field '_user@23046349' has not been initialized.
The relevant error-causing widget was
PostCard

Do you know how I can also fix this?

Thank you for your assistance

@jinosh05
Copy link

jinosh05 commented Sep 24, 2022 via email

@jinosh05
Copy link

jinosh05 commented Sep 25, 2022 via email

@jinosh05
Copy link

jinosh05 commented Sep 27, 2022 via email

@bozhen-ahmed964
Copy link

im not pretty sure if it LOL my Mac fooled my due to saved cache

@jinosh05
Copy link

jinosh05 commented Sep 27, 2022 via email

@RivaanRanawat
Copy link
Owner

In UserProvider class, add the following code:


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();
}
}

The change that we have made here is set the getUser's data type as User? which means it is of the type User which can or cannot be null.

In the screen where you're getting this error, AddPostScreen or any other screen, add the following code in build function:

final User? user = Provider.of<UserProvider>(context).getUser;
return user == null
? const Center(
child: CircularProgressIndicator(
),)
: _file == null
? Center(...)

What we are doing here is basically getting the user from our Provider and now since we have updated the getUser to return a data type of User?, check if user == null, if it is then we show a loading indicator to avoid the red screen other wise we just follow the widget tree we have typed in the video tutorials.

Note: This is not just necessary for AddPostScreen class, you can use it any file's build function where you think you'll get this error.

@RivaanRanawat RivaanRanawat added the waiting Waiting for Response label Sep 28, 2022
@jinosh05
Copy link

jinosh05 commented Oct 11, 2022 via email

@pnaskardev
Copy link

Okay so now the screen keeps on loading

@RivaanRanawat
Copy link
Owner

Okay so now the screen keeps on loading

Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that.

@Abhay014
Copy link

Hello guys,
I am also facing the same error.
I even cleared my Firestore database + Firebase Auth Console. The screen keeps on loading

@Abhay014
Copy link

solved it. it was a spelling mistake in collection('users') I had written collection('user')

@FrancisIje
Copy link

Hello, I have cleared firestore database and firebase Auth and the screen keeps loading

@FrancisIje
Copy link

Okay so now the screen keeps on loading

Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that.

Mine didn't work after that

@jinosh05
Copy link

jinosh05 commented Dec 6, 2022

I think I have fixed the issue , check my latest commit and close this issue

@huutan3621
Copy link

Hi, I'm having the same issue. Has anyone solved the problem yet?

@utkarshshukla03
Copy link

Okay so now the screen keeps on loading

Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that.

Mine didn't work after that

Francislje did you resolved the error?

@FrancisIje
Copy link

FrancisIje commented Dec 14, 2022 via email

@huutan3621
Copy link

On Tue, Dec 13, 2022 at 12:05 PM utkarshshukla03 @.> wrote: Okay so now the screen keeps on loading Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that. Mine didn't work after that Francislje did you resolved the error? — Reply to this email directly, view it on GitHub <#12 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/APX3MROFWABBW2H6PARTIY3WNBKBNANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.>
Yes I have solved this issue. Thanks

How did you solved this? Can I have your code to fix this?
Thank you so much

@utkarshshukla03
Copy link

On Tue, Dec 13, 2022 at 12:05 PM utkarshshukla03 @.> wrote: Okay so now the screen keeps on loading Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that. Mine didn't work after that Francislje did you resolved the error? — Reply to this email directly, view it on GitHub <#12 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/APX3MROFWABBW2H6PARTIY3WNBKBNANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.>
Yes I have solved this issue. Thanks

Can you please share how you solved? It will be really helpful

@utkarshshukla03
Copy link

utkarshshukla03 commented Dec 22, 2022

On Tue, Dec 13, 2022 at 12:05 PM utkarshshukla03 @.> wrote: Okay so now the screen keeps on loading Try clearing off your Firestore database + Firebase Auth Console and rechecking. Let me know if it works after that. Mine didn't work after that Francislje did you resolved the error? — Reply to this email directly, view it on GitHub <#12 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/APX3MROFWABBW2H6PARTIY3WNBKBNANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.>
Yes I have solved this issue. Thanks

@FrancisIje
please reply, thanks

@FrancisIje
Copy link

To be very honest, I can't remember how cause I went through a lot of trials and errors

@utkarshshukla03
Copy link

@FrancisIje can you please share your code? It will be really helpful

@RivaanRanawat
Copy link
Owner

Everyone getting this error, please share your GitHub repository.

@muhammetaydinn
Copy link

Guys I think I solved. Model wasnt nullable .

jsontodart
replace this:
model/user.dart

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  String? email;
  String? username;
  String? uid;
  String? bio;
  String? photoUrl;
  List<dynamic>? followers;
  List<dynamic>? following;

  User(
      {this.email,
      this.username,
      this.uid,
      this.bio,
      this.photoUrl,
      this.followers,
      this.following});

  User.fromJson(Map<String, dynamic> json) {
    email = json['email'];
    username = json['username'];
    uid = json['uid'];
    bio = json['bio'];
    photoUrl = json['photoUrl'];
    followers = json['followers'];
    following = json['following'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['email'] = email;
    data['username'] = username;
    data['uid'] = uid;
    data['bio'] = bio;
    data['photoUrl'] = photoUrl;
    data['followers'] = followers;
    data['following'] = following;
    return data;
  }

  static User fromSnap(DocumentSnapshot snap) {
    var snapshot = snap.data() as Map<String, dynamic>;
    return User(
        email: snapshot["email"],
        username: snapshot["username"],
        uid: snapshot["uid"],
        bio: snapshot["bio"],
        photoUrl: snapshot["photoUrl"],
        followers: snapshot["followers"],
        following: snapshot["following"]);
  }
}

mobile_screen_layout.dart

Widget build(BuildContext context) {
    model.User? user = Provider.of<UserProvider>(context).getUser;
    return Scaffold(
      body: Center(
        child: Text(user?.username ?? "Loading"),
      ),
    );
  }

responsive.dart

 @override
  void initState() {
    super.initState();
    addData();
  }

  addData() async {
    UserProvider _userProvider =
        Provider.of<UserProvider>(context, listen: false);
    await _userProvider.refreshUser();
  }

user.provider.dart

User? get getUser => _user;

@Ultra-rrich
Copy link

@muhammetaydinn when I try your solution, it kind of works but the profile picture doesn't display.
Thanks for your input.

However, please kindly check with your code for the responsive.dart file.
It's not complete. Otherwise kindly advise accordingly. Thank you.

@Ultra-rrich
Copy link

In UserProvider class, add the following code:


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();
}
}

The change that we have made here is set the getUser's data type as User? which means it is of the type User which can or cannot be null.

In the screen where you're getting this error, AddPostScreen or any other screen, add the following code in build function:

final User? user = Provider.of<UserProvider>(context).getUser;
return user == null
? const Center(
child: CircularProgressIndicator(
),)
: _file == null
? Center(...)

What we are doing here is basically getting the user from our Provider and now since we have updated the getUser to return a data type of User?, check if user == null, if it is then we show a loading indicator to avoid the red screen other wise we just follow the widget tree we have typed in the video tutorials.

Note: This is not just necessary for AddPostScreen class, you can use it any file's build function where you think you'll get this error.

Please @RivaanRanawat the screen keeps loading...?
Can you explain to as why we have to face this issue?

cos it's really delaying my progress!

@Ultra-rrich
Copy link

Everyone getting this error, please share your GitHub repository.

https://github.com/Ultra-rrich/Insta-Clone.git

this is mine. please help me solve the prooblem.

@muhammetaydinn
Copy link

I fix the problem with giving an error after click register without adding picture.

@dilipharish
Copy link

Guys I think I solved. Model wasnt nullable .

jsontodart replace this: model/user.dart

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  String? email;
  String? username;
  String? uid;
  String? bio;
  String? photoUrl;
  List<dynamic>? followers;
  List<dynamic>? following;

  User(
      {this.email,
      this.username,
      this.uid,
      this.bio,
      this.photoUrl,
      this.followers,
      this.following});

  User.fromJson(Map<String, dynamic> json) {
    email = json['email'];
    username = json['username'];
    uid = json['uid'];
    bio = json['bio'];
    photoUrl = json['photoUrl'];
    followers = json['followers'];
    following = json['following'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['email'] = email;
    data['username'] = username;
    data['uid'] = uid;
    data['bio'] = bio;
    data['photoUrl'] = photoUrl;
    data['followers'] = followers;
    data['following'] = following;
    return data;
  }

  static User fromSnap(DocumentSnapshot snap) {
    var snapshot = snap.data() as Map<String, dynamic>;
    return User(
        email: snapshot["email"],
        username: snapshot["username"],
        uid: snapshot["uid"],
        bio: snapshot["bio"],
        photoUrl: snapshot["photoUrl"],
        followers: snapshot["followers"],
        following: snapshot["following"]);
  }
}

mobile_screen_layout.dart

Widget build(BuildContext context) {
    model.User? user = Provider.of<UserProvider>(context).getUser;
    return Scaffold(
      body: Center(
        child: Text(user?.username ?? "Loading"),
      ),
    );
  }

responsive.dart

 @override
  void initState() {
    super.initState();
    addData();
  }

  addData() async {
    UserProvider _userProvider =
        Provider.of<UserProvider>(context, listen: false);
    await _userProvider.refreshUser();
  }

user.provider.dart

User? get getUser => _user;

Thanks a lot buddy,God Bless You

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
waiting Waiting for Response
Projects
None yet
Development

No branches or pull requests