Flutter Bloc 8.1 – why encountering “this.state invalid reference error”?

Issue

This Content is from Stack Overflow. Question asked by Haitham Dahrooj

I’m using the Bloc state mangement Library –
currently the version of the Library is 8.1.1
I’ve followed some guides and tutorials online , but I encountered an error regarding the reference to “this” in AddItem event functions below:

import 'dart:async';
import 'package:foodapptest/models/basket_model.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../models.dart';
import 'package:foodapptest/ResturantMenuItem.dart';
part 'basket_event.dart';
part 'basket_state.dart';

class BasketBloc extends Bloc<BasketEvent,BasketState>
//TO do fix bloc
{

  BasketBloc() : super(BasketLoading()) {
    on<BasketStart>(_onStartBasket);
    on<ItemAdd>(_onAddItem);
  }
  }


Future<void>  _onStartBasket(
      BasketStart event,
      Emitter<BasketState> emit,
      ) async {
    emit( BasketLoading());
    try{
      emit(BasketLoaded(basket: Basket(),),);
    }catch (e) {
      print(e);
    }


  }

Future<void> _onAddItem(
    ItemAdd event,
    Emitter<BasketState> emit,
    ) async {
  final state = this.state;
  if(state is BasketLoaded) {
    try {
      emit(BasketLoaded(basket: state.basket.copyWith(items: List.from(state.basket.items)..add(event.item))));
    } catch (_) {}

  }
}
     

  }

Picture:
the error

The error #2

all helps appreciated 🙂

Thank you!



Solution

Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?