我是初次接触并开发社交媒体应用程序的人。每次我想从Firebase获取数据时,都会收到错误消息 QueryDocumentSnapshot没有实例方法“ []”
这是我遇到错误的代码
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';
final usersRef = FirebaseFirestore.instance.collection('users');
class Timeline extends StatefulWidget {
@override
_TimelineState createState() => _TimelineState();
}
class _TimelineState extends State<Timeline> {
List<dynamic> users = [];
@override
void initState() {
// TODO: implement initState
getUsers();
//getUserById();
super.initState();
}
getUsers() async{
final QuerySnapshot snapshot = await usersRef.get();
setState(() {
users = snapshot.docs;
});
/*snapshot.docs.forEach((DocumentSnapshot doc){
print(doc.data());
print(doc.id);
print(doc.exists);
});*/
}
/*usersRef.get().then((QuerySnapshot snapshot){
snapshot.docs.forEach((DocumentSnapshot doc) {
print(doc.data());
});
});
}*/
/*getUserById() async{
final String id = "Hw75UQLfZPAZosI2O2Nu";
final DocumentSnapshot doc = await usersRef.doc(id).get();
print(doc.data());
print(doc.id);
print(doc.exists);
}*/
@override
Widget build(context) {
return Scaffold(
appBar: header(context, isAppTitle: true),
body: FutureBuilder(future: usersRef.get(),
builder: (context, snapshot) {
if (!snapshot.hasData){
return circularProgress();
}
final List<Text> children = snapshot.data.documents.map((doc) => Text(doc['username'])).toList();
return Container(
child: ListView(
children: children,
),
);
}
),
);
}
}
错误日志
Performing hot restart...
Syncing files to device sdk gphone x86 arm...
Restarted application in 706ms.
I/flutter ( 6385): User signed in!!!: GoogleSignInAccount:{displayName: Rinkumoni Khanikar, email: derekfrost621@gmail.com, id: 116999770966093637702, photoUrl: https://lh3.googleusercontent.com/a-/AOh14Gj1tc8cASVYMqeP-7NfiuWkfRQ5dnDHqNC2mhPNXA=s96-c}
I/flutter ( 6385): User signed in!!!: GoogleSignInAccount:{displayName: Rinkumoni Khanikar, email: derekfrost621@gmail.com, id: 116999770966093637702, photoUrl: https://lh3.googleusercontent.com/a-/AOh14Gj1tc8cASVYMqeP-7NfiuWkfRQ5dnDHqNC2mhPNXA=s96-c}
W/DynamiteModule( 6385): Local module descriptor class for providerinstaller not found.
I/DynamiteModule( 6385): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 6385): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state:
_FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4 new List.from (dart:core-patch/array_patch.dart:38:29)
#5 new List.of (dart:core-patch/array_patch.dart:68:17)
#6 ListIterable.toList (dart:_internal/iterable.dart:211:44)
#7 _TimelineState.build.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:97)
#8 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:740:55)
#9 StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
#10 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#11 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#12 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#13 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#14 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#15 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#16 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#17 StatelessElement.update (package:flutter/src/widgets/framework.dart:4627:5)
#18 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#19 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#20 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#21 ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#22 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#23 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#24 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#25 ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#26 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#27 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5566:32)
#28 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6001:17)
#29 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#30 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#31 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#32 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#33 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#34 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#35 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#36 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#37 ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#38 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#39 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#40 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#41 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#42 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#43 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#44 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5881:14)
#45 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#46 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#47 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#48 StatelessElement.update (package:flutter/src/widgets/framework.dart:4627:5)
#49 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#50 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5881:14)
#51 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#52 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#53 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#54 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#55 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#56 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#57 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#58 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#59 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#60 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#61 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#62 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#63 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#64 ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#65 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#66 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#67 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#68 ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#69 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#70 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#71 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#72 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#73 StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#74 Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#75 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#76 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#77 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#78 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33)
#79 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20)
#80 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
#81 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
#82 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1056:9)
#83 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:972:5)
#87 _invoke (dart:ui/hooks.dart:253:10)
#88 _drawFrame (dart:ui/hooks.dart:211:3)
(elided 3 frames from dart:async)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state: _FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4 new List.from (dart:core-patch/array_patch.dart:38:29)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: NoSuchMethodError: Class 'QueryDocumentSnapshot' has no instance method '[]'.
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state: _FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4 new List.from (dart:core-patch/array_patch.dart:38:29)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
pubspec.yaml
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cloud_firestore: 0.14.0+2
image_picker: ^0.6.0+2
firebase_storage: 4.0.0
firebase_auth: 0.18.0+1
google_sign_in: ^4.0.1+1
geolocator: 6.0.0+4
uuid: ^2.0.0
image: ^2.0.7
animator: 2.0.1
cupertino_icons: 1.0.0
path_provider: 1.6.14
firebase_messaging: 7.0.0
timeago: 2.0.27
cached_network_image: 2.3.2+1
firebase_core: ^0.5.0
flutter_svg:
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
uses-material-design: true
fonts:
- family: Signatra
fonts:
- asset: assets/fonts/Signatra.ttf
assets:
- assets/images/google_signin_button.png
- assets/images/upload.svg
- assets/images/search.svg
- assets/images/activity_feed.svg
- assets/images/no_content.svg
main.dart
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FriendsHive',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepPurple,
accentColor: Colors.teal,
),
home: Home(),
);
}
}
Cloud Firestore
我知道我犯了一些错误,请任何人指出我的错误。 谢谢!!!
答案 0 :(得分:0)
如我的评论所述,您似乎是在以空值调用['username']。尝试先为null咀嚼。这可能有效:
替换此:
final List<Text> children = snapshot.data.documents.map((doc) => Text(doc['username']);
与此:
final List<Text> children = snapshot.data.documents.map(
(doc){
if(doc!=null){
return Text(doc['username']);
}
else{
return Text(“No Data”);
}
}).toList();
答案 1 :(得分:0)
只有几处需要修复。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';
final usersRef = FirebaseFirestore.instance.collection('users');
class Timeline extends StatefulWidget {
@override
_TimelineState createState() => _TimelineState();
}
class _TimelineState extends State<Timeline> {
/// What you're going to be getting back from your query is a QuerySnapshot, which will contain a List of DocumentSnapshots
Future<QuerySnapshot> querySnapshot;
@override
void initState() {
/// Here you set your querySnapshot to what you get from your database call
querySnapshot = getUsers();
super.initState();
}
Future<QuerySnapshot> getUsers() async {
return await usersRef.get();
}
@override
Widget build(context) {
return Scaffold(
appBar: header(context, isAppTitle: true),
body: FutureBuilder(
future: querySnapshot, // This is what you return in your future builder
builder: (context, snapshot) {
if ((snapshot.connectionState == ConnectionState.done) && (snapshot.hasData)){
List<dynamic> usernames = []; // This is where the usernames you get from Firebase will be saved
List<DocumentSnapshot> documentSnapshot = snapshot.documents; // Putting the snapshot into a List of DocumentSnapshot
for(DocumentSnapshot doc in documentSnapshot) {
Map<String, dynamic> mappedData = doc.data;
String un = mappedData["username"]; // Extracting every username in the document snapshot
usernames.add(un);
}
final List<Text> children = usernames.map((user) => Text(user)).toList(); /// Mapping the username into a Text Widget, I don't know if I did this part right
return Container (
child: ListView(
children: children,
),
);
} else {
return circularProgress(); // Check that you got this part right
}
}
),
);
}
}
这应该为您工作。让我知道它是否有效! :)