Home > Software engineering >  How to handle the null check operator exception?
How to handle the null check operator exception?

Time:06-19

I am working on a simple Todo App, here is my code.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:todo_app/screens/new_task.dart';

class MyHome extends StatefulWidget {
const MyHome({Key? key}) : super(key: key);

@override
_myHomeState createState() => _myHomeState();
}

 class _myHomeState extends State<MyHome> {
 String uid = ' ';
 @override
 void initState() {
 getUid();
 super.initState();
  }

 getUid() async {
 FirebaseAuth auth = FirebaseAuth.instance;
 final User? user = await auth.currentUser;
 setState(() {
    uid = user!.uid;
  });
 }

 @override
 Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
    title: Text('TODO'),
    backgroundColor: Colors.purple,
  ),
  body: Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    color: Colors.white10,
    child: StreamBuilder<QuerySnapshot<Map<String,dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection('tasks')
          .doc(uid)
          .collection('myTasks')
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: CircularProgressIndicator(),
          );
        } else {
          final docs = snapshot.data!.docs;
          return ListView.builder(
            itemCount: docs.length,
            itemBuilder: (context, index) {
              return Container(
                child: Column(
                  children: [Text(docs[index]['title'])],
                ),
              );
            },
          );
        }
      },
    ),
      ),
    floatingActionButton: FloatingActionButton(
    child: Icon(
      Icons.add,
      color: Colors.white,
    ),
    backgroundColor: Theme.of(context).primaryColor,
    onPressed: () {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => AddTask()));
    },
   ),
   );
  }
 }

Only one point, I am using null check operator, first setState(() { uid = user!.uid;});} When I remove this, flutter throws the error to put the null check operator. So, please help me, I am a beginner........................................................................................................................................................................................................................................................

CodePudding user response:

and if you use user?.uid; sometimes it requires default value, so in that case you can set a default value user?.uid ?? "Information Not Available" for not getting error.

CodePudding user response:

the problem is user can be null because is type User? and the question mark means its value can be null, make it of type User instead of User?

CodePudding user response:

instead of user!.uid; use user?.uid ?? "";. If you use ? it means that the user can be null

CodePudding user response:

If you’re sure that an expression with a nullable type isn’t null, you can

add ! to make Dart treat it as non-nullable.

user?.uid this means you expect user model has uid value. and it should be there if not there it will give you an exception.

Example: Let,

int? x;

x! - confident value never be null.

x??0 - If x is null, there it will be 0;

if(x != null){ then use your x value }

that's how null safety helps to handle nullable values in dart/flutter.

CodePudding user response:

Getting the current firebase user is no longer async. (It hasn't been for about a year.) You're reading an old tutorial. Please find one written in the the past nine months.

  • Related