Flutter:带有初始网络请求的ChangeNotifierProvider

时间:2019-08-13 13:35:45

标签: flutter flutter-provider

我有一个代表电影列表的小部件,在我的模型中,我有getMovies()函数,该函数从网络请求中检索电影列表:

class myWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(myWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        canvas = vispy.app.Canvas()
        lay = QtWidgets.QVBoxLayout(self.ui.frameFor3d) # create layout
        lay.addWidget(canvas.native)

if __name__ == '__main__': 
    app = QtWidgets.QApplication([])
    application = myWindow()
    application.show()
    vispy.app.run()
    # sys.exit(app.exec())

然后从小部件中,我要根据请求的状态构建布局:

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;
    }
  }
}

问题是,如何在小部件初始化开始时触发网络调用getMovies()?我尝试在不同的位置手动调用getMovies()方法,但是我遇到了错误,或者每次小部件调用其build()方法时,该调用都在重复。

谢谢。

1 个答案:

答案 0 :(得分:1)

使用FutureProvider修复:

  @override
  Widget build(BuildContext context) {
    return FutureProvider<List<Movie>>.value(
      value: _model.getMovies(),
      initialData: List<Movie>(),
      catchError: (context, error) {
        return null;
      },
      child: Consumer<List<Movie>>(
        builder: (context, data, widget) {
          // ...
        },
      ),
    );
  }