我正在实现一个需要递归调用以获取所有数据的api。我已经实现了具有recursive transformer
的Bloc组件。但是,似乎转换器一直在递归调用上返回空累加器。
comments_bloc.dart
class CommentsBloc {
final _repository = Repository();
final _commentsFetcher = PublishSubject<int>();
final _commentsOutput = BehaviorSubject<Map<int, Future<ItemModel>>>();
// Stream Getters
Observable<Map<int, Future<ItemModel>>> get itemWithComments =>
_commentsOutput.stream;
// Sink getters
Function(int) get fetchItemWithComments => _commentsFetcher.sink.add;
CommentsBloc() {
_commentsFetcher.stream
.transform(_commentsTransformer())
.pipe(_commentsOutput);
}
_commentsTransformer() {
return ScanStreamTransformer<int, Map<int, Future<ItemModel>>>(
(cache, int id, index) {
cache[id] = _repository.fetchItem(id);
cache[id].then((ItemModel item) {
item.kids.forEach((kidId) => fetchItemWithComments(kidId));
});
},
<int, Future<ItemModel>>{},
);
}
dispose() {
_commentsFetcher.close();
_commentsOutput.close();
}
}
app.dart
return MaterialPageRoute(
builder: (BuildContext context) {
final itemId = int.parse(settings.name.replaceFirst('/', ''));
final commentsBloc = CommentsProvider.of(context);
commentsBloc.fetchItemWithComments(itemId);
return NewsDetail(itemId: itemId);
},
);
错误
E/flutter (17142): [ERROR:flutter/shell/common/shell.cc(178)] Dart Error: Unhandled exception:
E/flutter (17142): NoSuchMethodError: The method '[]=' was called on null.
E/flutter (17142): Receiver: null
E/flutter (17142): Tried calling: []=(19307509, Instance of 'Future<ItemModel>')
E/flutter (17142): #0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1112:29)
E/flutter (17142): #1 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (17142): #2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
_commentsTransformer 仅执行在cache[id] = _repository.fetchItem(id);
;
上引发错误的第一个实例
答案 0 :(得分:1)
显然cache
是null
。这是因为您没有在变压器的累加器函数中返回cache
。您需要返回它,因为它不是箭头函数。
_commentsTransformer() {
return ScanStreamTransformer<int, Map<int, Future<ItemModel>>>(
(cache, int id, index) {
cache[id] = _repository.fetchItem(id);
cache[id].then((ItemModel item) {
item.kids.forEach((kidId) => fetchItemWithComments(kidId));
});
return cache; // <-- code fix here.
},
<int, Future<ItemModel>>{},
);
}