何时或在什么情况下我应该在 Flutter Bloc 中使用 RepositoryProvider?

问题描述 投票:0回答:1

我在没有 RepositoryProvider 的情况下从 api 获取数据,但我在文档上看到了 RepositoryProvider。 有什么区别?或者我应该用于数据吗?

当我使用 RepositoryProvider 时,我无法更改状态。例如,我尝试使用 RefreshIndicator 但状态没有重建。

flutter repository-pattern bloc provider flutter-bloc
1个回答
0
投票

RepositoryProvider 是一个 Flutter 小部件,它通过 RepositoryProvider.of(context) 为其子部件提供存储库。它用作依赖项注入 (DI) 小部件,以便可以将存储库的单个实例提供给子树内的多个小部件。 BlocProvider 应该用于提供块,而 RepositoryProvider 应该仅用于存储库。

RepositoryProvider 用法

class WeatherRepository {
  WeatherRepository({
    MetaWeatherApiClient? weatherApiClient
  }) : _weatherApiClient = weatherApiClient ?? MetaWeatherApiClient();

  final MetaWeatherApiClient _weatherApiClient;

  Future<Weather> getWeather(String city) async {
    final location = await _weatherApiClient.locationSearch(city);
    final woeid = location.woeid;
    final weather = await _weatherApiClient.getWeather(woeid);
    return Weather(
      temperature: weather.theTemp,
      location: location.title,
      condition: weather.weatherStateAbbr.toCondition,
    );
  }
}

void main() {
  runApp(WeatherApp(weatherRepository: WeatherRepository()));
}

class WeatherApp extends StatelessWidget {
  const WeatherApp({
            required WeatherRepository weatherRepository,
            Key? key, 
  })
      : _weatherRepository = weatherRepository,
        super(key: key);

  final WeatherRepository _weatherRepository;

  @override
  Widget build(BuildContext context) {
    return RepositoryProvider.value(
      value: _weatherRepository,
      child: BlocProvider(
        create: (_) => ThemeCubit(),
        child: WeatherAppView(),
      ),
    );
  }
}

class WeatherPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => WeatherCubit(context.read<WeatherRepository>()),
      child: WeatherView(),
    );
  }
}

更多信息请参见文档。但在一般存储库中,它与数据有关,而块 - 它与状态管理有关。

© www.soinside.com 2019 - 2024. All rights reserved.