我正在使用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: (){
}
),
);
},
),
}