我有一个代表电影列表的小部件,在我的模型中,我有 getMovies() 函数,它从网络请求中检索电影列表:
enum MovieListState { IDLE, LOADING, ERROR }
class MovieListModel extends ChangeNotifier {
MovieListModel(this._client);
GatewayClient _client;
MovieListState _viewState = MovieListState.LOADING;
MovieListState get viewState => _viewState;
set viewState(MovieListState value) {
_viewState = value;
notifyListeners();
}
Future<List<Movie>> getMovies() async {
try {
viewState = MovieListState.LOADING;
var movies = await _client.getMovies();
viewState = MovieListState.IDLE;
return movies;
} on KoException catch (e) {
viewState = MovieListState.ERROR;
throw e;
}
}
}
然后从小部件中,我想根据请求的状态构建布局:
@override
Widget build(BuildContext context) {
state = Provider.of<AppState>(context);
var model = MovieListModel(Provider.of<GatewayClient>(context));
return ChangeNotifierProvider<MovieListModel>.value(
value: model,
child: Consumer<MovieListModel>(builder: (context, model, child) {
if (model.viewState == MovieListState.IDLE) {
return _getList(); // Method which generates the content with the retrieved values
} else if (model.viewState == MovieListState.LOADING) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Center(
child: Text(_static.translate(context).movieListError),
);
}
}));
}
问题是,如何在小部件初始化的一开始就触发网络调用 getMovies() ?我试图在不同的点手动调用 getMovies() 方法,但我有一个错误,或者每次小部件调用其 build() 方法时调用都会重复。
提前致谢。