flutter – Kindly help me I am facing this issue during state management and using provider (firebase): “Error: Unexpected null value.at Object.thr

I am doing state management and using providers here are my file of code: I was trying to acess my user details stored through providers in firebase but I get the null value error. I also call the init state but still i am getting this error. Like I can access the user details by creating the instance of firebaseAuth but not from provider (State management)..

………………………………………………………………………………………………………………………………………… …………

dependencies:
  cloud_firestore: ^3.1.17
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.3.19
  firebase_core: ^1.17.1
  firebase_storage: ^10.2.17
  flutter:
    sdk: flutter
  flutter_screenutil: ^5.5.3+2
  image_picker: ^0.8.5+3
  intl: ^0.17.0
  provider: ^6.0.3
  uuid: ^3.0.6

main.dart file

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutterfire/Providers/user_provider.dart';
import 'package:flutterfire/screens/feed_screen_layout.dart';
import 'package:flutterfire/screens/home_page.dart';
import 'package:flutterfire/screens/signUp/sign_up_screen.dart';
import 'package:flutterfire/screens/signin_screen/signin_screen.dart';
import 'package:flutterfire/widgets/post_card.dart';
import 'package:provider/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      options: FirebaseOptions(
          apiKey: "AIzaSyBQe67EDTzq4mDi-f5m0jHviug1OBwqf0M",
          appId: "1:910237534972:web:97b6e3351874da52426579",
          messagingSenderId: "910237534972",
          projectId: "flutterfire-5a8c2",
          storageBucket: "flutterfire-5a8c2.appspot.com"));
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider(create: (_) => userProvider())],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        theme: ThemeData.dark()
            .copyWith(scaffoldBackgroundColor: Colors.grey.shade800),
        home: FeedScreen(),
        ),
    );
  }
}

………post card file…………….

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutterfire/Providers/user_provider.dart';
import 'package:flutterfire/Providers/user_provider.dart';
import 'package:flutterfire/Providers/user_provider.dart';
import 'package:flutterfire/models/user.dart' as model;    
import 'package:flutterfire/resources/firestore_methods.dart';
import 'package:flutterfire/screens/comment_screen.dart';
import 'package:flutterfire/widgets/like_animation.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../Providers/user_provider.dart';

class PostCard extends StatefulWidget {
  final snap;
  const PostCard({Key? key, required this.snap}) : super(key: key);

  @override
  State<PostCard> createState() => _PostCardState();
}

class _PostCardState extends State<PostCard> {
  FirebaseAuth _auth = FirebaseAuth.instance;
  bool isLikeAnimating = false;
  // final model.User user = Provider.of<userProvider>(context).getuser;
  // userProvider _userProvider = userProvider();
  @override
  void initState() {
    super.initState();
    addData();
  }

  addData() async {
    userProvider _userProvider = Provider.of(context, listen: false);
    await _userProvider.refreshUser();
  }

  @override
  Widget build(BuildContext context) {
    final model.User? user = Provider.of<userProvider>(context).getuser;
return ScreenUtilInit(
  designSize: Size(390, 844),
  builder: (context, child) => Container(
    color: Colors.grey.shade800,
    padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 20.w),
    child: Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(
            vertical: 4.h,
          ),
          child: Row(
            children: [
              CircleAvatar(
                radius: 16.r,
                backgroundImage: NetworkImage(widget.snap["profileImage"]),
              ),
              SizedBox(
                width: 8.w,
              ),
              Expanded(
                child: Text(
                  widget.snap['username'],
                  style: TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 10.sp),
                ),
              ),
              IconButton(
                  onPressed: () {
                    showDialog(
                        context: context,
                        builder: (context) => Dialog(
                              child: ListView(
                                padding:
                                    EdgeInsets.symmetric(horizontal: 0.w),
                                shrinkWrap: true,
                                children: [
                                  'Delete',
                                  'Report',
                                ]
                                    .map((e) => InkWell(
                                          onTap: () {},
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 16.w,
                                                vertical: 12.h),
                                            child: Text(e),
                                          ),
                                        ))
                                    .toList(),
                              ),
                            ));
                  },
                  icon: Icon(Icons.more_vert))
            ],
          ),
        ),
        //Image Section
        // Container(
        //   height: MediaQuery.of(context).size.height * 0.45,
        //   width: double.infinity,
        //   alignment: Alignment.center,
        GestureDetector(
          onDoubleTap: () async {
            await FirestoreMethods().likePost(
              widget.snap['postId'],
              // _auth.currentUser?.uid,
              user!.uid,
              widget.snap['likes'],
            );
            setState(() {
              isLikeAnimating = true;
            });
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              Image.network(
                widget.snap['postUrl'],
                fit: BoxFit.cover,
                height: MediaQuery.of(context).size.height * 0.45,
                width: double.infinity,
              ),
              AnimatedOpacity(
                duration: const Duration(milliseconds: 300),
                opacity: isLikeAnimating ? 1 : 0,
                child: LikeAnimation(
                  child: Icon(
                    Icons.favorite,
                    size: 120,
                    color: Colors.white,
                  ),
                  isAnimating: isLikeAnimating,
                  duration: const Duration(milliseconds: 400),
                  onEnd: () {
                    setState(() {
                      isLikeAnimating = false;
                    });
                  },
                ),
              )
            ],
          ),
        ),
        // ),
        //like , comment, share
        Row(
          children: [
            LikeAnimation(
                isAnimating:
                    widget.snap['likes'].contains(_auth.currentUser?.uid),
                smallLike: true,
                child: widget.snap['likes'].contains(_auth.currentUser?.uid)
                    ? IconButton(
                        onPressed: () {},
                        icon: Icon(Icons.favorite),
                        color: Colors.red,
                      )
                    : const Icon(Icons.favorite_border)),
            IconButton(
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => CommentScreen()));
                },
                icon: Icon(Icons.comment_outlined)),
            IconButton(onPressed: () {}, icon: Icon(Icons.send)),
            Expanded(
                child: Align(
              alignment: Alignment.bottomRight,
              child: IconButton(
                  onPressed: () {},
                  icon: Icon(
                    Icons.bookmark_border,
                  )),
            ))
          ],
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              DefaultTextStyle(
                style: Theme.of(context).textTheme.subtitle2!.copyWith(
                      fontWeight: FontWeight.w800,
                    ),
                child: Text(
                  '${widget.snap['likes'].length} likes',
                  style: Theme.of(context).textTheme.bodyText2,
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(top: 8.h),
                child: RichText(
                  text: TextSpan(
                    style: TextStyle(color: Colors.white),
                    children: [
                      TextSpan(
                          text: '${widget.snap['username']} ',
                          style: TextStyle(fontWeight: FontWeight.bold)),
                      TextSpan(
                        text: widget.snap['description'],
                        // style: TextStyle(fontWeight: FontWeight.bold)
                      ),
                    ],
                  ),
                ),
              ),
              InkWell(
                onTap: () {},
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 4.h),
                  child: Text(
                    'View all 112 Comments',
                    style: TextStyle(fontSize: 16.sp, color: Colors.grey),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(vertical: 4.h),
                child: Text(
                  DateFormat.yMMMd().format(
                    widget.snap['datePublished'].toDate(),
                  ),
                  style: TextStyle(fontSize: 16.sp, color: Colors.grey),
                ),
              ),
            ],
          ),
        )
      ],
    ),
  ),
);

} }

………………..user provider file………………………

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterfire/models/user.dart' as model;
import 'package:flutterfire/resources/auth_method.dart';

class userProvider with ChangeNotifier {
  // FirebaseAuth _auth = FirebaseAuth.instance;
  model.User? _user;
  model.User? get getuser => _user;
  Authmethods _authmethods = Authmethods();

  Future<void> refreshUser() async {
    model.User user = await _authmethods.getUserDetails();
    _user = user;
    notifyListeners();
  }
}

Leave a Comment