Search code examples
flutterdartblocrxdartstream-builder

Error: "Bad state: No element" when using BLoC_pattern with a bool value


I'm using bloc_pattern package and I have a bloc that will manage a favorite IconButton, I have a bool variable called _isFavorite that will pass to the stream showing if the item is favorite or not. When I instantiate the FavoriteBloc I get the error: "Bad state: No element". I seeded with a value "false" but it doesn't work. I followed the example of the package, does anyone know how I fix it?

class FavoritesBloc extends BlocBase {

  FavoritesBloc();

  bool _isFavorite;

  var _favoriteController = BehaviorSubject<bool>.seeded(false);

  Stream<bool> get outFavorite => _favoriteController.stream;

  Sink<bool> get inFavorite => _favoriteController.sink;


  @override
  void dispose() {
    _favoriteController.close();
    super.dispose();
  }


}

Main

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return BlocProvider(
      blocs: [
              Bloc((i)=> FavoritesBloc()) ,
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: HomeScreen(),
        theme: ThemeData(
          primaryColor: Colors.cyan[700],
        ),
      ),
    );
  }

}

The class where I call the FavoriteBloc:

class DetailScreen extends StatelessWidget {

  final favoritesBloc = BlocProvider.getBloc<FavoritesBloc>();

  @override
  Widget build(BuildContext context) {

    return WillPopScope(
      onWillPop: (){

        Navigator.of(context).pop();


      },
      child: Material(
        child: OKToast(
          child: SafeArea(
            child: Scaffold(
              body: Stack(
                children: <Widget>[

                  StreamBuilder(
                    stream: favoritesBloc.outFavorite,
                    builder: (context, snapshot){

                      bool isFavorite = snapshot.data;

                      return Align(
                        alignment: Alignment.topRight,
                        heightFactor: 200,
                        child: IconButton(
                            icon: Icon(
                              FontAwesomeIcons.solidHeart,
                              color: isFavorite == true ? Colors.redAccent : Colors.white,
                              size: 35,
                            ),
                            onPressed: (){

                            }
                        ),
                      );
                    },
                  ),

}

Solution

  • Verify your imports in main.dart