Flutter通过ProxyProvider注入返回null。

7

GitHub示例项目

这是我想注入WebParserApi和ProxyProvider的简单类,但我得到了null值。

class RetrievePageSummarizedInformation extends StatesRebuilder {
  BuiltUserProfile builtUserProfile = BuiltUserProfile();
  final WebParserApi _api;

  RetrievePageSummarizedInformation({WebParserApi api}) : _api = api;

  retrievePageProfileInfo(BuildContext context,String username) async {
    //_preparePageProfileCache();
    //WebParserApi _api = Provider.of<WebParserApi>(context);
    return await _api.getProfileRetrieveFromParser(username);
  }

  void _preparePageProfileCache() async {
    await KvStore().createTable('userProfile');
  }
}

主函数:
void main() async {
  Provider.debugCheckInvalidValueType = null;

  _setUpLogging();

  runApp(MultiProvider(providers: providers, child: OKToast(child: StartupApplication())));
}

proxyProvider 实现:

List<SingleChildCloneableWidget> providers = [
    ...independentServices, 
    ...dependentServices, 
    ...uiConsumableProviders
];

List<SingleChildCloneableWidget> independentServices = [
  Provider(
    builder: (_) => WebParserApi.create(),
    dispose: (_, WebParserApi service) => service.client.dispose(),
  )
];

List<SingleChildCloneableWidget> dependentServices = [
  ProxyProvider<WebParserApi, RetrievePageSummarizedInformation>(
    builder: (context, api, retrievePageSummarizedInformation) => RetrievePageSummarizedInformation(api: api),
  )
];

List<SingleChildCloneableWidget> uiConsumableProviders = [

];

这是我的WebParserApi类的实现:

@ChopperApi(baseUrl: '/')
abstract class WebParserApi extends ChopperService {
  @Get(path: '{token}')
  Future<Response<BuiltUserProfile>> getProfileRetrieveFromParser(@Path() String username);

  static WebParserApi create() {
    final client = ChopperClient(
        client: http.IOClient(
          HttpClient()..connectionTimeout = const Duration(seconds: 60),
        ),
        baseUrl: 'https://www.sample.com',
        services: [
          _$WebParserApi(),
        ],
        converter: BuiltValueConverter(),
        interceptors: [
          HeadersInterceptor({'Content-Type': 'application/json'}),
          HttpLoggingInterceptor(),
        ]);
    return _$WebParserApi(client);
  }
}

问题出在这里。将WebParserApi注入到 RetrievePageSummarizedInformation 类中:

return Injector<RetrievePageSummarizedInformation>(
  models: [() => RetrievePageSummarizedInformation()],
  builder: (context, model) => Stack(
    children: <Widget>[
      ),
    ],
  ),
);

我在GitHub上创建了一个简单的项目,链接为https://github.com/MahdiPishguy/proxy_provider_sample。当我尝试在主类中使用_pageInformation.pageProfile('test')时,PageInformation类中的_api变量为空。


返回 null 是什么意思? - Rémi Rousselet
@RémiRousselet 在 RetrievePageSummarizedInformation 类中,_api 为空。 - DolDurma
@RémiRousselet 的问题是将 WebParserApi 传递给 RetrievePageSummarizedInformation 类的构造函数作为 _api 参数。 - DolDurma
@RémiRousselet,你能帮我解决这个ProxyProvider返回null的问题吗? - DolDurma
你添加了太多无关的代码。因此我不明白问题出在哪里。 - Rémi Rousselet
1
@RémiRousselet 我在Github上创建了一个简单的项目,链接为https://github.com/MahdiPishguy/proxy_provider_sample。 在main类中使用_pageInformation.pageProfile('test');时,在PageInformation类的_api变量为空。 - DolDurma
2个回答

0

您遇到了一个问题:PageInformation _pageInformation = PageInformation();。您最好从context中获取_pageInformation,而不是手动创建新的空实例,其中apinull。这样做可以解决问题:


  ...

  @override
  Widget build(BuildContext context) {

    // here
    Provider.of<PageInformation>(context).pageProfile('test');

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(

...

https://pub.dev/packages/provider#reading-a-value

最简单的读取值的方法是使用静态方法Provider.of<T>(BuildContext context)。此方法将从与传递的BuildContext相关联的小部件开始查找并返回找到的类型为T的最近变量(如果未找到,则抛出)。

希望能对您有所帮助。

0

我的问题已经解决了,我们必须在使用ProxyProvider定义的类上使用Provider.of(context)

class RetrievePageSummarizedInformation extends StatesRebuilder {
  BuiltUserProfile builtUserProfile = BuiltUserProfile();
  final WebParserApi _api;

  RetrievePageSummarizedInformation({@required WebParserApi api}) : _api = api;

  getPageProfileInfo(String username) async {
    final res = await _api.getSimpleProfileInformation(username);
    return res;
  }
}

注入解决方案:

models: [() => RetrievePageSummarizedInformation(api:Provider.of(context))],

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接