skip to Main Content

If I run the app and the last user account stays logged and click on logs out, this null check operator is used on a null value is what appears in the emulator, and I don’t know where the exact error to solve it.

this is my main.dart code

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:water_reminder_app/screens/home_page.dart';
import 'package:water_reminder_app/screens/start_page.dart';
import 'package:water_reminder_app/services/notify_service.dart';
import 'package:water_reminder_app/widgets/database.dart';
import 'package:water_reminder_app/widgets/user_data.dart';
import 'firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'model/pages_names.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  unawaited(MobileAds.instance.initialize());

  await NotificationServices().init();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  runApp(
    ChangeNotifierProvider(
        create: (context) => CloudDataProvider(), child: const MyApp()),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({
    super.key,
  });

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? profileImagePath;
  User? user;

  @override
  void initState() {
    super.initState();
    user = FirebaseAuth.instance.currentUser;
  }

  @override
  Widget build(BuildContext context) {
    final cloudDataProvider =
        Provider.of<CloudDataProvider>(context, listen: false);
    final weight = cloudDataProvider.weight;
    final unit = cloudDataProvider.unit;
    final bedtime = cloudDataProvider.bedtime;
    final wakeUpTime = cloudDataProvider.wakeUptime;

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => UserDataProvider(),
        ),
        ChangeNotifierProvider(
          create: (context) => CloudDataProvider(),
        ),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: user == null
            ? const StartPage()
            : HomePage(
                weight: weight ?? 0,
                unit: unit ?? '',
                bedTime: bedtime ?? '',
                wakeUpTime: wakeUpTime ?? ''),
        onGenerateRoute: MyRoutes.genrateRoute,
      ),
    );
  }
}

And this is the CloudDataProvider file

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';

class CloudDataProvider extends ChangeNotifier {
  double? weight;
  String? unit;
  String? bedtime;
  String? wakeUptime;

  void fetchUserData() async {
    final User? user = FirebaseAuth.instance.currentUser;

    if (user != null) {
      final userDoc =
          FirebaseFirestore.instance.collection('users').doc(user.uid);

      final userSnapshot = await userDoc.get();

      weight = userSnapshot['weight'] as double;
      unit = userSnapshot['unit'] as String;
      bedtime = userSnapshot['bedtime'] as String;
      wakeUptime = userSnapshot['wake-up time'] as String;
    }

    notifyListeners();
  }
}

You can find the whole app in this link gitHub link

I tried to use ?? instead of ! that I found it in this link Null check operator used on a null value but the error still there. anyone can know how to fix this problem

2

Answers


  1. just add some simple null check & u r good to go,

    void fetchUserData() async {
        final User? user = FirebaseAuth.instance.currentUser;
        if (user != null) {
          final userDoc =
              FirebaseFirestore.instance.collection('users').doc(user.uid);
          final userSnapshot = await userDoc.get();
          weight = userSnapshot['weight'] !=null ? userSnapshot['weight'] as double : null;
          unit = userSnapshot['unit'] !=null ? userSnapshot['unit'].toString() : null;
          bedtime = userSnapshot['bedtime'] != null ? userSnapshot['bedtime'].toString() : null;
          wakeUptime = userSnapshot['wake-up time'] !=null ? userSnapshot['wake-up time'].toString() : null;
        }
        notifyListeners();
      }
    
    Login or Signup to reply.
  2. The error should tell you on what line exactly the error happens. I’ve tried your project and it’s actually on login, not logout that a null error happens for me. and the error says

    E/flutter ( 4930): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
    E/flutter ( 4930): #0      _HomeState.getData.<anonymous closure> (package:water_reminder_app/screens/home.dart:103:62)
    E/flutter ( 4930): #1      State.setState (package:flutter/src/widgets/framework.dart:1203:30)
    E/flutter ( 4930): #2      _HomeState.getData (package:water_reminder_app/screens/home.dart:93:5)
    

    The second line says home.dart:103:62 meaning it’s in that file on line 103, which is

          userDataProvider.amount =
              sharedPreferences.getDouble('$userAuthID + amount')!;
    

    Here you use ! on something that returns null, so maybe change it to

          userDataProvider.amount =
              sharedPreferences.getDouble('$userAuthID + amount') ?? 0.0;
    

    Maybe it’s not the same error that you have, but you should be able to find the exact spot where the error happens in the same way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search