Search code examples
flutterdartbloc

Flutter: How can I assign results from a BlocBuilder to a IconData?


I have this piece of Dart code used in a Flutter app. It's using the flutter_bloc library.

icon: BlocBuilder<SongsBloc, SongsState>(
    builder: (context, state) {
       var songSelected = context
         .watch<SongsBloc>()
         .state
         .getSongById(widget.song.id!)
         .selected!;
       return songSelected
           ? FontAwesomeIcons.circleCheck
           : FontAwesomeIcons.circle;
   },
)

Here, icon is IconData?. The idea is to update the icon on song selection change. But I get the following error message.

The argument of type 'BlocBuilder<SongsBloc, SongsState>' cannot be assigned to the parameter of type 'IconData?'

From the code above BlocBuilder returns IconData, therefore the error is not expected.

What am I missing or doing wrong?


Solution

  • Getting data inside method.

    final currentState = BlocProvider.of<SongsBloc>(context).state
     //if you have multiple state check here with `state is StateA`
    bool songSelected = currentState.getSongById(widget.song.id!).selected??false;
    final icon =  songSelected ? FontAwesomeIcons.circleCheck : FontAwesomeIcons.circle;
    
    // now iuse this `icon` on params.
    

    For widget case,You can use BlocBuilder on top of this widget.

    BlocBuilder<SongsBloc, SongsState>(
         builder: (context, state) {
           var songSelected =  state.getSongById(widget.song.id!).selected??false;
           return Icon( songSelected
                 ? FontAwesomeIcons.circleCheck
                 : FontAwesomeIcons.circle);