我正在 Flutter 中制作电影列表应用程序,当我打开应用程序时,我正在显示观看次数最多的电影列表。当我单击一个按钮时,我会获取新数据并将其添加到接收器,然后将其发送到 StreamBuilder 并且应该用新数据刷新屏幕。
但这不会发生。我无法理解为什么!
这是我的存储库代码:
class MoviesRepository {
final _movieApiProvider = MovieApiProvider();
fetchAllMovies() async => _movieApiProvider.fetchMovieList();
fetchAllSimilarMovies(genreIdeas) async => await _movieApiProvider.fetchMoviesLikeThis(genreIdeas);
fetchTopRatedMovies() async => await _movieApiProvider.fetchTopRatedMovieList();
}
这是我的块代码:
class MoviesBloc {
final _moviesRepository = MoviesRepository();
final _moviesFetcher = BehaviorSubject<Result>();
Sink<Result> get allMovies => _fetcherController.sink;
final _fetcherController = StreamController<Result>();
Observable<Result> get newResults => _moviesFetcher.stream;
fetchAllMovies() async {
Result model = await _moviesRepository.fetchAllMovies();
allMovies.add(model);
}
fetchTopRatedMovies() async{
Result model = await _moviesRepository.fetchTopRatedMovies();
allMovies.add(model);
}
dispose() {
_moviesFetcher.close();
_fetcherController.close();
}
MoviesBloc() {
_fetcherController.stream.listen(_handle);
}
void _handle(Result event) {
_moviesFetcher.add(event);
}
}
final bloc = MoviesBloc();
更新
这是我的 StreamBuilder 代码:
class HomeScreenListState extends State<HomeScreenList> {
@override
void initState() {
super.initState();
print("init");
bloc.fetchAllMovies();
}
@override
void dispose() {
super.dispose();
bloc.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Result>(
builder: (context, snapshot) {
if (snapshot.hasData) {
print("new data is here");
return buildList(snapshot);
} else if (snapshot.hasError) {
return Text('Error!!');
}
return Center(
child: CircularProgressIndicator(),
);
},
stream: bloc.newResults,
);
}
}
这是触发获取新数据并将其添加到接收器的按钮:
child: RaisedButton(onPressed: () {
bloc.fetchTopRatedMovies();
},
此按钮获取收视率最高的电影并添加到同一个接收器。现在 StreamBuilder 应该按照我的想法获取新数据。
问题出在哪里??