複数のドキュメントの中でフィールドが足りない場合、
リスト表示使用とすると以下のようなエラーになります。
field does not exist within the DocumentSnapshotPlatform
以下のようなデータ構造となっていることを想定しています。
ドキュメント1
-id
-name
ドキュメント2
-id
-name
ドキュメント3
-id
この場合ドキュメント3のnameが取得できずエラーとなっています。
この回避方法を知りたいです。
よろしくお願いします。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答1件
0
参考ページ
https://stackoverflow.com/questions/64949640/flutter-unhandled-exception-bad-state-field-does-not-exist-within-the-documen
一応この方法でエラーが出なくなりました。よろしければ参考にされてください。
コレクション"Japan"のデータ
ドキュメント "Chiba" フィールド"title": "千葉県"
ドキュメント "Saitama" フィールド"title": "埼玉県"
ドキュメント "Tokyo" フィールド無し
画面表示
千葉県
埼玉県
title not found
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:provider/provider.dart'; import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(MaterialApp(home: MyApp())); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: Nihon(), ); } } class Nihon extends StatefulWidget { @override State<Nihon> createState() => _NihonState(); } class _NihonState extends State<Nihon> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("日本"), ), body: ChangeNotifierProvider<ProductListModel>( create: (_) => ProductListModel()..getProducts(), child: Consumer<ProductListModel>( builder: (context, model, child) { final products = model.products; if(products.isEmpty){ return CircularProgressIndicator(); } return SafeArea( child: Column(children: <Widget>[ Text(products[0].title), Text(products[1].title), Text(products[2].title), ]), ); }, ), ), ); } } class ProductModel { String title; ProductModel( this.title, ); } class ProductListModel extends ChangeNotifier { List<ProductModel> products = []; Future getProducts() async { var collection = await FirebaseFirestore.instance.collection("Japan").get(); products = //↓(A)これだと'title'フィールドが無い場合(Tokyo)にエラーが出る。 //collection.docs.map((doc) => ProductModel(doc['title'])).toList(); //↓(B)これだとエラーが出ない。 collection.docs.map((doc){ return doc.data().containsKey('title') ? ProductModel(doc['title']) : ProductModel('title nof found'); }).toList(); this.products = products; notifyListeners(); } }
投稿2022/10/01 05:57
総合スコア615
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。