【发布时间】:2020-07-19 21:45:08
【问题描述】:
又回来了。我根据这个帖子中的建议重构了我的代码:Flutter Multiple Blocs and NamedRoutes
但是,由于将我的块从主材质应用树移动到路由器页面,因此数据没有加载,因为快照为空。
路由器:
class AppRouter {
final _centresBloc = CentresBloc();
Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case routes.CentreSelectScreenRoute:
return MaterialPageRoute(
builder: (_) => BlocProvider(
bloc: _centresBloc,
child: CentreSelectScreen(),
),
);
default:
return MaterialPageRoute(builder: (context) => HomeScreen());
}
以及 CentreSelectScreen 类本身
class _CentreSelectScreenState extends State<CentreSelectScreen> {
@override
Widget build(BuildContext context) {
final _centresBloc = BlocProvider.of<CentresBloc>(context);
return Scaffold(
body: Container(
child: StreamBuilder<List<ClimbingCentre>>(
stream: _centresBloc.centres,
builder: (context, snapshot) {
print('snapshot == ${snapshot.data}'); //is always null now
if (snapshot.hasData) {
// If there are no centres (data), display this message.
if (snapshot.data.length == 0) {
return Text('No Centres listed');
}...
blocpprovider 最初位于 centerselect 屏幕类中,一切正常,但自从移动它后,它就不起作用了,我似乎不知道为什么。
当应用程序首次加载时,博客本身似乎已正确初始化,因为它正在打印出所有正确的信息。来自 CentresBloc:
void getCentres() async {
// Retrieve all the centres from the database
List<ClimbingCentre> centres = await ClimbDB.db.getCentres();
// Add all of the centres to the stream so we can grab them later from our pages
_inCentres.add(centres);
print('BLOC incentres is $centres'); //this works and prints all centres when the app first loads...
}
非常感谢任何帮助。
编辑添加 CentresBloc 类
import 'dart:async';
import 'package:flutterapp/data/database.dart';
import 'package:flutterapp/models/centre_model.dart';
import 'bloc_provider.dart';
class CentresBloc implements BlocBase {
final _centresController = StreamController<List<ClimbingCentre>>.broadcast();
// Input stream. Add centres to the stream using this variable.
StreamSink<List<ClimbingCentre>> get _inCentres => _centresController.sink;
// Output stream. This one will be used within our pages to display the centres.
Stream<List<ClimbingCentre>> get centres => _centresController.stream;
CentresBloc() {
// Retrieve all the climbing centres on initialization
getCentres();
}
@override
void dispose() {
_centresController.close();
}
void getCentres() async {
// Retrieve all the centres from the database
List<ClimbingCentre> centres = await ClimbDB.db.getCentres();
// Add all of the centres to the stream so we can grab them later from our pages
_inCentres.add(centres);
print('CentreBloc _incentres is: $centres'); //this prints the correct centres when the app is first loaded
}
【问题讨论】:
-
请出示
CentresBloc类 -
感谢@IgorKharakhordin,我已将 CentresBloc 添加到原帖中。