Aabis Ahmed Hassan
Aabis Ahmed Hassan

Reputation: 11

Null Check Operator used on a null value in my flutter app

I'm currently developing a Firebase Instagram Clone, and I've faced an issue with the 'Add Post' screen. When the user navigates to this screen, they're able to select an image to upload. However, immediately after selecting the image, the screen turns red, displaying an error message:

Null Check Operator used on a null value

I'm adding the relevant code snippet from the add post file, along with the error message, and a link to my GitHub repository for this project.

GitHub: https://github.com/Aabis-Ahmed-Hassan/Instagram-Clone-Firebase

Add Post Screen Code:

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_clone_firebase/post/upload_post_data.dart';
import 'package:instagram_clone_firebase/utils/colors.dart';
import 'package:instagram_clone_firebase/utils/constants/padding.dart';
import 'package:instagram_clone_firebase/view_modal/user_provider.dart';
import 'package:provider/provider.dart';

import '../utils/utils.dart';

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

  @override
  State<AddPost> createState() => _AddPostState();
}

class _AddPostState extends State<AddPost> {
  var _postImage;

  chooseImage(BuildContext context) async {
    return showDialog(
        context: context,
        builder: (context) => SimpleDialog(
              title: Text(
                'Pick an Image',
              ),
              children: [
                SimpleDialogOption(
                  onPressed: () async {
                    Navigator.pop(context);
                    _postImage = await Utils.pickImage(ImageSource.camera);
                    setState(() {});
                  },
                  child: Text(
                    'Capture a Picture',
                  ),
                ),
                SimpleDialogOption(
                  onPressed: () async {
                    Navigator.pop(context);
                    _postImage = await Utils.pickImage(ImageSource.gallery);
                    setState(() {});
                  },
                  child: Text(
                    'Choose from Gallery',
                  ),
                ),
                SimpleDialogOption(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text(
                    'Cancel',
                  ),
                ),
              ],
            ));
  }

  TextEditingController _postDescription = TextEditingController();

  bool loading = false;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _postDescription.dispose();
  }

  postIt(
    String description,
    String username,
    String profileImage,
    String uid,
  ) async {
    setState(() {
      loading = true;
    });

    await uploadPostData(_postImage, uid, description, username, profileImage);

    setState(
      () {
        loading = false;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height * 1;
    double width = MediaQuery.of(context).size.width * 1;

    // UserModal user = Provider.of<UserProvider>(context, listen: false).getUser;
    UserProvider user = Provider.of<UserProvider>(context, listen: false);
    print('build');
    return _postImage == null
        ? Center(
            child: IconButton(
              onPressed: () async {
                await chooseImage(context);
              },
              icon: Icon(
                Icons.upload,
              ),
            ),
          )
        : Scaffold(
            appBar: AppBar(
              backgroundColor: mobileBackgroundColor,
              leading: Icon(
                Icons.arrow_back,
              ),
              title: Text(
                'Add Post',
              ),
              centerTitle: false,
              actions: [
                InkWell(
                  onTap: () {
                    return postIt(
                      _postDescription.text.toString(),
                      user.getUser.username.toString(),
                      user.getUser.imageUrl.toString(),
                      user.getUser.uid.toString(),
                    );
                  },
                  child: Text(
                    'Post',
                    style: TextStyle(
                      color: Colors.blue,
                      fontWeight: FontWeight.w500,
                      fontSize: 16,
                    ),
                  ),
                ),
                SizedBox(
                  width: width * 0.035,
                ),
              ],
            ),
            body: Padding(
              padding: EdgeInsets.symmetric(horizontal: width * padding),
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 4,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            CircleAvatar(
                              radius: width * 0.075,
                              backgroundImage: NetworkImage(
                                user.getUser.toString(),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 9,
                        child: TextFormField(
                          controller: _postDescription,
                          decoration: InputDecoration(
                            hintText: 'Write a caption...',
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        // child: Image.file(_postImage!),
                        child: _postImage != null
                            ? Image.file(_postImage!)
                            : Container(),
                      ),
                    ],
                  ),
                  Divider(),
                  Container(),
                  loading
                      ? CircularProgressIndicator()
                      : Container(
                          height: 50,
                          width: 50,
                          color: Colors.blue,
                        ),
                ],
              ),
            ),
          );
  }
}

Error:

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building AddPost(dirty, dependencies: [MediaQuery, _LocalizationsScope-[GlobalKey#8b487]], state: _AddPostState#be0c8):
Null check operator used on a null value

The relevant error-causing widget was:
AddPost AddPost:file:///C:/Users/aabis/StudioProjects/Instagram-Clone-Firebase/lib/view/responsiveness/mobile_layout.dart:18:5
When the exception was thrown, this was the stack:
#0 UserProvider.getUser (package:instagram_clone_firebase/view_modal/user_provider.dart:8:33)
#1 _AddPostState.build (package:instagram_clone_firebase/view/add_post.dart:159:38)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:5592:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5480:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5643:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:5196:7)
#6 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2904:19)
#7 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:989:21)
#8 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:448:5)
#9 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1386:15)
#10 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1311:9)
#11 SchedulerBinding.scheduleWarmUpFrame. (package:flutter/src/scheduler/binding.dart:1034:7)
#15 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
(elided 3 frames from class _Timer and dart:async-patch)\

I've tried different things, but all in vain.

EDIT I've found the problem. The problem was I deleted the data in firestore but I didn't delete the users (in firebase console authentication tab). So, I was able to login to the app but there was error while showing user's profile picture on the screen.

Upvotes: 0

Views: 62

Answers (1)

Kaushik Chandru
Kaushik Chandru

Reputation: 17802

You used user.getUser() inplace of user.getUser().imageUrl.toString() in line number 159

Upvotes: 0

Related Questions