skip to Main Content

I am new to Flutter. It is giving me an error saying that I have used null check operator on a null value

Links for reference:
https://github.com/ahkharsha/pregAthI/blob/main/lib/widgets/community-chat/community_list_drawer.dart
https://github.com/ahkharsha/pregAthI/blob/main/lib/auth/auth_controller.dart

My code:

  class CommunityDrawer extends ConsumerWidget {
  const CommunityDrawer({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userProvider)!;
    final isGuest = !user.isAuthenticated;

  ...

  final userProvider = StateProvider<ChatUserModel?>((ref) => null);

3

Answers


  1. It appears that you are using the null check operator (!) on the userProvider in the CommunityDrawer widget, and this is causing the null check operator on a null value error. To handle this try this:

     final user = ref.watch(userProvider); // <-- Null check operator here
     final isGuest = (!user?.isAuthenticated) ?? true;
    
    Login or Signup to reply.
  2. To avoid the null check error, you should perform a null check before accessing properties or methods on the user variable. You can do this using the null-aware operator (?.)

    final user = ref.watch(userProvider);
    final isGuest = user?.isAuthenticated ?? false;
    
    
    Login or Signup to reply.
  3. In your code, you’re not using either user nor isGuest in any of your widgets. You’re just passing the value to the onTap callback. In that case, you don’t need to use ref.watch in the build method, but instead, use ref.read inside the onTap callback.

    onTap: () {
      // ...
    
      final user = ref.read(userProvider); // Just let it nullable
      
      // Check if the value of user is null. This is the case when
      // the user tap the ListTile before the value for user is ready.
      // Just do nothing or for better UX you can make your UI show
      // something else
      if (user == null) return;
    
      final isGuest = user.isAuthenticated; // Now this isn't nullable
      if (!isGuest) {
        // ...
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search