簡體   English   中英

Flutter:當它是“FutureProvider()”時找不到“Provider.of(context)”

[英]Flutter: `Provider.of(context)` cannot be found when it is a `FutureProvider()`

我的小部件樹中有一個提供程序,我調用Provider.of<List<...>>(context)來找到它。 如果它是任何類型的提供者,它可以正常工作,但是,一旦將提供者從Provider() (例如)更改為FutureProvider()它就不起作用。

我沒有更改樹中的任何小部件,也沒有更改導航器中的 position。 Provider.of()工作正常,但是一旦我將它設置為FutureProvider()就不起作用了。

編輯:我的代碼看起來像這樣:

內部小部件構建:

return FutureProvider(
      initialData: [],
      create: (_) =>
          DatabaseService(uid: _auth.getUser()!.uid).getJournalEntries(),
      catchError: (context, error) {
        print(error.toString());
      },
      ...
}

然后其中一個孩子是另一個小部件,這是它的構建 function:

List<JournalEntryData> entries =
        Provider.of<List<JournalEntryData>>(context);
    return ElevatedButton(
        onPressed: () {
          print(entries);
        },
        child: Text('print provider data'));
}

我收到以下錯誤:

錯誤:在此 TestButton 小部件上方找不到正確的 Provider<List>

發生這種情況是因為您使用的BuildContext不包括您選擇的提供者。 有幾種常見的場景:

  • 您在main.dart中添加了一個新提供程序並執行了熱重載。 要修復,請執行熱重啟。

  • 您嘗試讀取的提供程序位於不同的路徑中。

    提供者是“范圍的”。 因此,如果您在路由中插入提供程序,那么其他路由將無法訪問該提供程序。

  • 您使用的BuildContext是您嘗試讀取的提供程序的祖先。

    確保 TestButton 在您的 MultiProvider/Provider<List> 下。 這通常發生在您創建提供程序並嘗試立即讀取它時。

    例如,而不是:

     Widget build(BuildContext context) { return Provider<Example>( create: (_) => Example(), // Will throw a ProviderNotFoundError, because `context` is associated // to the widget that is the parent of `Provider<Example>` child: Text(context.watch<Example>()), ), }

    考慮像這樣使用builder

     Widget build(BuildContext context) { return Provider<Example>( create: (_) => Example(), // we use `builder` to obtain a new `BuildContext` that has access to the provider builder: (context) { // No longer throws return Text(context.watch<Example>()), } ), }

問題是小部件樹中有一個提供者: 小部件樹

用任何其他類型的提供者替換FutureProvider()可以使其工作,但我需要一個FutureProvider()

我沒有定義FutureProvider()的類型,所以它是dynamic的,但在我的Provider.of()調用中,我指定了導致問題的類型。 指定FutureProvider()的類型應該可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM