我在应用程序中应用了Bloc模式,通过底部导航更改屏幕时遇到了问题。
我尝试进行流广播,但是更改屏幕后数据消失了。
这是我的Home类,它代表主屏幕。
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final DepartmentBloc departmentBloc = BlocProvider.getBloc<DepartmentBloc>();
final PromotionProductBloc promotionProductBloc = BlocProvider.getBloc<PromotionProductBloc>();
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CustomText(
text: "Promoções",
fontSize: 20.0,
padding: EdgeInsets.only(left: 12.0),
),
StreamBuilder(
stream: promotionProductBloc.outPromotionProducts,
builder: (context, snapshot) {
if (snapshot.hasData)
return Container(
height: 230.0,
child: ListView.builder(
padding: EdgeInsets.only(
left: 12.0, right: 12.0, bottom: 10.0),
itemBuilder: (context, index) {
return PromotionProductCard(snapshot.data[index]);
},
itemCount: snapshot.data.length,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
),
);
else
return Container(
height: 200.0,
);
},
),
CustomText(
text: "Categorias",
fontSize: 20.0,
padding: EdgeInsets.only(left: 12.0, top: 20.0, bottom: 10.0),
),
StreamBuilder(
stream: departmentBloc.outDepartments,
builder: (context, snapshot) {
if (snapshot.hasData)
return Container(
height: 120.0,
child: ListView.builder(
padding: EdgeInsets.only(left: 12.0, right: 12.0),
itemBuilder: (context, index) {
return CategoryCard(snapshot.data[index]);
},
itemCount: snapshot.data.length,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
),
);
else
return Container(
height: 100.0,
);
},
),
],
),
),
);
}
这是访问服务以获取数据并打开Stream出口的类。
class DepartmentBloc extends BlocBase {
DepartmentService departmentService;
List<Department> departments;
final StreamController<List<Department>> _departmentController = StreamController<List<Department>>();
Stream<List<Department>> get outDepartments => _departmentController.stream;
DepartmentBloc() {
departmentService = DepartmentService();
getAll();
}
void getAll() async {
departments = await departmentService.getAll();
_departmentController.sink.add(departments);
}
@override
void dispose() {
_departmentController.close();
super.dispose();
}
}
PromotionProductBloc与DepartmentBloc相同,仅更改服务访问权限。
我正在使用底部导航,然后转到另一个屏幕并返回以下错误:流已被收听。
答案 0 :(得分:0)
尝试
final StreamController<List<Department>> _departmentController = StreamController.broadcast<List<Department>>();
似乎您正在使用单个订阅流控制器。他们只能听一次。它们的一个优点是,第一个侦听器将在订阅前收到那些发出的事件。广播流不能保证这种行为,但是可以多次订阅。