Search code examples
flutterbloccubit

TypeError: Cannot read properties of null (reading 'getAllPostsRep') bloc cubit flutter


i'm new in bloc, i have static data and need to write clean code using data layer "repositry and model" before write this line in initstate, the Loading widget was only work but i discover that i should write cubit dunction in the initstate to emit the state of loaded, notice that i didn't use loading state. just initial and loaded have this error

TypeError: Cannot read properties of null (reading 'getAllPostsRep')

The relevant error-causing widget was
LayoutBuilder LayoutBuilder:file:///C:/Users/Michael/Desktop/task/New/lib/presentation/screens/home_screen.dart:34:24
When the exception was thrown, this was the stack
packages/facebookui/business_logic/cubit/posts_cubit.dart 15:38                                                       getAllPosts

after written this line in initstate

class _FeedState extends State<Feed> {
  List<PostModel> allPosts = [];

  @override
  void initState() {
    super.initState();
    BlocProvider.of<PostsCubit>(context).getAllPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 2,
      child: Align(
        alignment: AlignmentDirectional.topStart,
        child: SingleChildScrollView(
          child: Align(
            alignment: AlignmentDirectional.topStart,
            child: Column(
              children: [
                Stories(), //stories widget
                Card(
                  child: Column(
                    children: [
                      WhatsOnYourMind(), //img,textfield of create post
                      CustomDivider(),
                      LiveSection(), //live, video and photos section
                      SizedBox(
                        height: 20,
                      )
                    ],
                  ),
                ),
                //create room and rooms
                Rooms(),
                //all posts
                BlocBuilder<PostsCubit, PostsState>(
                  builder: (context, state) {
                    if (state is PostsLoaded) {
                      setState(() {
                        allPosts = (state).postsList;
                      });
                      return Posts(allPosts: allPosts);
                    } else {
                      return Loading();
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

this is repositry that get static data from flie post

class PostsRepository {
  //charactersWebServices

  Future<List<PostModel>> getAllPostsRep() async {
    await Future.delayed(const Duration(seconds: 2));
    //posts is a const data
    return posts;
  }
}

this is state

part of 'posts_cubit.dart';

@immutable
abstract class PostsState {}

class PostsInitial extends PostsState {}

class PostsLoaded extends PostsState {
  final List<PostModel> postsList;
  PostsLoaded(this.postsList);
}

this is cubit

class PostsCubit extends Cubit<PostsState> {
  final PostsRepository postsRepository;
  List<PostModel> allposts = [];

  PostsCubit(this.postsRepository) : super(PostsInitial());

  List<PostModel> getAllPosts() {
    postsRepository.getAllPostsRep().then((value) {
      emit(PostsLoaded(value));
      allposts = value;
    });
    return allposts;
  }
}

this is the const data

List<PostModel> posts = [
  PostModel(
      name: 'Abdullah Ghayad',
      time: 5,
      text:
          'The APIC Text is the most comprehensive and up-to-date reference for infection prevention and control (IPC). Written, edited, and reviewed by more than 200 subject matter experts, it reflects the latest guidelines, regulations, and standards of practice.The APIC Text\’s 11 sections and 125 peer-reviewed chapters are broad ranging, covering everything from fundamental principles, microbiology, epidemiology, and surveillance to more specialized topics, including specialty care populations, special pathogens, occupational health, and supportive care.',
      comments: 5,
      like: 50,
      profileImage:
          'http://c.files.bbci.co.uk/C870/production/_112921315_gettyimages-876284806.jpg',
      images: [
        'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCZlf5lc5tX-0gY-y94pGS0mQdL-D0lCH2OQ&usqp=CAU'
      ]),
]

Solution

  • because postsRepository is null, you need to initialized it

      final PostsRepository postsRepository = PostsRepository();
    

    and remvoe it from constructor