在 BLoC 模式中传递参数 Flutter(Stream Controller)
Posted
技术标签:
【中文标题】在 BLoC 模式中传递参数 Flutter(Stream Controller)【英文标题】:Pass parameter in BLoC pattern Flutter(Stream Controller) 【发布时间】:2022-01-15 20:21:44 【问题描述】:我是 Flutter 的新手,不确定这是否是正确的方法。我正在按照 YouTube 教程使用 TMDB API 创建电影应用程序,并尝试将 category.dart(下面的评论)中的“genreId”传递给 MovieBloc.dart。是否可以发送“genreId”?如果是,我该如何通过?如果没有,最好的方法是什么? 谢谢
category.dart
final movieBloc = MovieBloc();
setState(()
selectedGenre = genre.id;
movieBloc.eventSink.add(MovieControlAction.byGenre); // send genreId through here??
);
movie_bloc.dart
import 'dart:async';
import 'package:flutter_api/Model/movie.dart';
import 'package:flutter_api/Service/api_service.dart';
enum MovieControlAction fetch, delete, byGenre,
class MovieBloc
final service = ApiService();
final _stateStreamController = StreamController<List<Movie>>();
StreamSink<List<Movie>> get _movieSink => _stateStreamController.sink;
Stream<List<Movie>> get movieStream => _stateStreamController.stream;
final _eventStreamController = StreamController<MovieControlAction>();
StreamSink<MovieControlAction> get eventSink =>
_eventStreamController.sink; //input
Stream<MovieControlAction> get _eventStream =>
_eventStreamController.stream; //output
MovieBloc()
_eventStream.listen((event) async
if (event == MovieControlAction.fetch)
try
var movies = await service.getNowPlayingMovie();
if (movies != null)
_movieSink.add(movies);
else
_movieSink.addError('Null');
on Exception catch (e)
print(e);
_movieSink.addError('Something went wrong');
else if (event == MovieControlAction.byGenre)
var moviesByGenre = await service.getMovieByGenre(genreId);
if (moviesByGenre != null)
_movieSink.add(moviesByGenre);
else
_movieSink.addError('Null');
);
void dispose()
_stateStreamController.close();
_eventStreamController.close();
【问题讨论】:
【参考方案1】:您可以将其传递给 MovieBloc,如下所示:
final movieBloc = MovieBloc(genreId: genre.id);
然后在 MovieBloc 类中创建一个构造函数:
class MovieBloc
final String genreId; // String, int, whatever type it is
MovieBloc(
required this.genreId,
);
如果你想使用真正的 Bloc,你应该像这样扩展 MovieBloc:
class MovieBloc extends Bloc<MovieEvent, MovieState>
目前看起来您并没有使用实际的 Bloc 模式。请查看official Bloc documentation。我保证 - 它非常有用。
【讨论】:
以上是关于在 BLoC 模式中传递参数 Flutter(Stream Controller)的主要内容,如果未能解决你的问题,请参考以下文章
Flutter Bloc 框架 实现 HTTP + JSON 通讯