3

我正在使用bloc_pattern包,我有一个 bloc 将管理一个收藏的 IconButton,我有一个名为 _isFavorite 的 bool 变量,它将传递给流,显示该项目是否是收藏的。当我实例化 FavoriteBloc 时,我收到错误:“Bad state: No element”。我播种了一个值“false”,但它不起作用。我按照包的示例进行操作,有人知道我如何解决吗?

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();
  }


}

主要的

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],
        ),
      ),
    );
  }

}

我称之为 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: (){

                            }
                        ),
                      );
                    },
                  ),

}
4

4 回答 4

3

在 main.dart 中验证您的导入

于 2019-07-09T20:16:21.667 回答
1

尝试访问空可迭代的第一个元素时,我遇到了同样的问题。

@override
Widget build(BuildContext context) {
  return BlocProvider<MyBloc>(
    create: (context) {
      var list = myIterable.keys.first; // keys was empty
      var myBloc = MyBloc();
      return myBloc;
      }
       return schuldenBloc;
    },
  );
}

错误坏状态:没有元素发生,因为我试图在.firstkeysBlocProvider

var list = myIterable.keys.first; // keys was empty
于 2020-06-04T10:16:33.460 回答
0

您忘记通知 StreamBuilder 类型,在这种情况下是StreamBuilder<bool>()

我认为这就是问题所在。

于 2019-07-09T18:23:26.153 回答
0

在你把 var _favoritecontroller puts as final 看它是否有效的集团类中

于 2019-07-09T22:03:44.050 回答