dart Flutter:如何将BlocBuilder中的结果分配给IconData?

zmeyuzjn  于 2023-03-15  发布在  Flutter
关注(0)|答案(1)|浏览(117)

我在Flutter应用程序中使用了这段Dart代码,它使用flutter_bloc库。

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

这里,iconIconData?。我们的想法是在歌曲选择改变时更新图标。但是我得到了下面的错误消息。

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

根据上面的代码,BlocBuilder返回IconData,因此该错误不是预期错误。
我错过了什么或做错了什么?

ars1skjm

ars1skjm1#

正在获取方法内的数据。

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.

对于小部件的情况下,您可以使用BlocBuilder在这个小部件的顶部.

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

相关问题