FutureBuilder 使用時に Snapshot has neither data nor error
とエラー発生
- 環境
- Dart SDK version: 2.9.2 (stable) (Wed Aug 26 12:44:28 2020 +0200) on "macos_x64"
- Flutter 1.20.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 216dee60c0 (2 weeks ago) • 2020-09-01 12:24:47 -0700
Engine • revision d1bc06f032
□ エラー内容
...snip
════════ Exception caught by widgets library ═══════════════════════════════════
The following StateError was thrown building HomepageFeaturedWidget(dirty):
Bad state: Snapshot has neither data nor error
...snip
□ 問題のコード
Container(
child: FutureBuilder<List<Series>>(
future: seriesList,
builder: (context, snapshot) {
return HomepageFeaturedWidget(snapshot: snapshot);
},
),
),
□ 解決策
-
seriesList
はFuture<T>
であることから、非同期でデータを取得 - そのため、Widget 生成直後は
HomepageFeaturedWidget
の引数が空であるため、エラーが発生した様子 - このことから snapshot を未取得時に対する処理を追加
Container(
child: FutureBuilder<List<Series>>(
future: seriesList,
builder: (context, snapshot) {
+ if (!snapshot.hasData) {
+ return const Center(child: CircularProgressIndicator());
+ }
return HomepageFeaturedWidget(snapshot: snapshot);
},
),
),
// ...snip
□ メモ
公式サイトを参照すると、取得時、例外時、未取得時
で処理を分割
if (snapshot.hasData) {
// ...snip
} else if (snapshot.hasError) {
// ...snip
} else {
// ...snip
}