尝试用不同的表达式替换对实例成员的引用

问题描述

我正在使用 Riverpod 获取 Api 并在应用程序中显示,我的方法“getMovieList()”需要一个字符串,但在下面的代码中我收到此错误: "无法在初始化程序中访问实例成员“pageNumber”。 尝试用不同的表达式替换对实例成员的引用dartimplicit_this_reference_in_initializer"

class StateManager {

  final String pageNumber;
  StateManager(this.pageNumber);
  
  static final movieStateFuture = FutureProvider<List<Movie>>((ref) async {
    return ApiSetup.getMovieList(pageNumber); // The error is Here "The instance member 'pageNumber' can't be accessed in an initializer."

  });
}
class ApiSetup {
  static List<Movie> parsePhotos(String responseBody) {
    List<Movie> listMovies = [];
    for (var mov in jsonDecode(responseBody)['results']) {
      final movie = Movie.fromJson(mov);
      listMovies.add(movie);
    }
    return listMovies;
  }

  static Future<List<Movie>> getMovieList(String pageNum) async {
    final response = await http.get(Uri.parse(
        "https://api.themoviedb.org/3/movie/Now_playing?api_key=${Constants.apiKey}&language=en-US&page=$pageNum"));
    if (response.statusCode == 200) {
      return compute(parsePhotos,response.body);
    } else {
      print("Error here");
    }
    throw Exception("Some Random Error");
  }
}

解决方法

您不能从 static 方法内部引用非静态成员。您的 pageNumber 是属于 StateManager 的实例/对象的属性,而静态方法属于该类。

如果您想在访问未来时使用 pageNumber,请尝试改用 family 提供程序:

static final movieStateFuture = FutureProvider.family<List<Movie>,int>( //<-- Add '.family' modifer and 'datatype' of the argument
  (ref,pageNum) async { //<-- Second argument to create method is the parameter you pass
    return ApiSetup.getMovieList(pageNum);
  }
);

现在在调用 movieStateFuture 时,像这样传入参数:

watch(movieStateFuture(/*PAGE_NUMBER_HERE*/));