RivaanRanawat / instagram-flutter-clone

Responsive Instagram Clone developed with Flutter & Firebase
https://youtu.be/BBccK1zTgxw
858 stars 474 forks source link

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

Open javaskrskr opened 2 years ago

javaskrskr commented 2 years ago

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 commented 2 years ago

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

javaskrskr commented 2 years ago

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

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

lomanu4 commented 2 years ago

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 commented 2 years ago

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 commented 1 year ago

@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 commented 1 year ago

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

jammydman commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

Yes I'm trying to fix that issue. Will give it a try and let you know

On Sat, Sep 24, 2022, 7:07 PM jammydman @.***> wrote:

Thank you for your response, this fixed some of the issue. I am not getting an error: Exception caught by widgets library ═══════════════════════════════════ LateInitializationError: Field @.***' 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

— Reply to this email directly, view it on GitHub https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1256971277, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMIVT5LIWDRPT4NVE2RWH3DV737ZFANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.***>

jinosh05 commented 1 year ago

Hello I have made a commit, can you check that and let me know?

On Sat, Sep 24, 2022, 8:44 PM Jinosh Prabhuraj @.***> wrote:

Yes I'm trying to fix that issue. Will give it a try and let you know

On Sat, Sep 24, 2022, 7:07 PM jammydman @.***> wrote:

Thank you for your response, this fixed some of the issue. I am not getting an error: Exception caught by widgets library ═══════════════════════════════════ LateInitializationError: Field @.***' 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

— Reply to this email directly, view it on GitHub https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1256971277, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMIVT5LIWDRPT4NVE2RWH3DV737ZFANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.***>

jinosh05 commented 1 year ago

Sounds good 😊

On Tue, Sep 27, 2022, 3:29 PM bozhen ahmed @.***> wrote:

` getData() async { setState(() { isLoading = true; }); try { var userSnap = await FirebaseFirestore.instance .collection('users') .doc(widget.uid) .get();

// get post lENGTH var postSnap = await FirebaseFirestore.instance .collection('posts') .where('uid', isEqualTo: FirebaseAuth.instance.currentUser?.uid) .get();

postLen = postSnap.docs.length; userData = userSnap.data()!; followers = userSnap.data()!['followers'].length; following = userSnap.data()!['following'].length; isFollowing = userSnap .data()!['followers'] .contains(FirebaseAuth.instance.currentUser?.uid); setState(() {}); } catch (e) { showSnackBar( context, e.toString(), ); } setState(() { isLoading = false; });

}`

i'ver fixed it by small change is this method in Profile_Screen

— Reply to this email directly, view it on GitHub https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1259271577, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMIVT5M2ZBFU4RQXRPY6RKLWALARDANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.***>

bozhen-ahmed964 commented 1 year ago

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

jinosh05 commented 1 year ago

Can you try at real device once again?

On Tue, Sep 27, 2022, 3:42 PM bozhen ahmed @.***> wrote:

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

— Reply to this email directly, view it on GitHub https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1259285730, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMIVT5I7YCJ2RPMBAFAL4NLWALCAXANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.***>

RivaanRanawat commented 1 year ago

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.

jinosh05 commented 1 year ago

Ok, I'll check it out.

On Tue, Sep 27, 2022, 3:20 PM bozhen ahmed @.***> wrote:

Hello I have made a commit, can you check that and let me know? On Sat, Sep 24, 2022, 8:44 PM Jinosh Prabhuraj @.***> wrote: … <#m-3140787578887795477>

i'ver checked your commit i think that there is still user null Error in user profile screen it wont show user profile

— Reply to this email directly, view it on GitHub https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1259260296, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMIVT5NQJM2L6CBKPOW2MJ3WAK7M3ANCNFSM54OGGZ7Q . You are receiving this because you commented.Message ID: @.***>

pnaskardev commented 1 year ago

Okay so now the screen keeps on loading

RivaanRanawat commented 1 year ago

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 commented 1 year ago

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

Abhay014 commented 1 year ago

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

FrancisIje commented 1 year ago

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

FrancisIje commented 1 year ago

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 commented 1 year ago

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

huutan3621 commented 1 year ago

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

utkarshshukla03 commented 1 year ago

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 commented 1 year ago

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 https://github.com/RivaanRanawat/instagram-flutter-clone/issues/12#issuecomment-1348198156, 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

huutan3621 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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

utkarshshukla03 commented 1 year ago

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

RivaanRanawat commented 1 year ago

Everyone getting this error, please share your GitHub repository.

muhammetaydinn commented 1 year ago

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 commented 1 year ago

@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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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

dilipharish commented 1 year ago

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