问题
I am trying to build an app using Flutter and Firestore. When loading a Collection from Firestore using StreamBuilder to display it in a ListView, I get the following error
The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter (26287): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#d5638):
I/flutter (26287): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
I/flutter (26287): where
I/flutter (26287): _InternalLinkedHashMap is from dart:collection
I/flutter (26287): Map is from dart:core
I/flutter (26287): String is from dart:core
This is how I want to get data from the DocumentSnapshot
class Creator {
const Creator({this.creatorId, this.name});
Creator.fromDoc(DocumentSnapshot doc) : this.fromMap(doc.data);
Creator.fromMap(Map<String, dynamic> map) :
assert(map.containsKey('creatorId'),
assert(map.containsKey('name'),
this ( creatorId: map['creatorId'], name: map['name'] );
/*
...
*/
}
And how I want to use it
return Scaffold(
appBar: AppBar(title: new Text('Creators')),
body: StreamBuilder<QuerySnapshot>(
stream: CreatorRepo.getCreators().map<List<Creator>>((creators) {
return creators.documents.map<Creator>((c) => Creator.fromSnapshot(c)).toList();
}),
builder: (BuildContext context, snapshot) {
if ( snapshot.hasData ) {
return ListView.builder(
itemCount: snapshot.data.length,
builder: (context, index) {
final creator = snapshot.data[index];
return ExpansionTile(
title: Text(creator.name),
children: [
Text(creator.creatorId),
],
);
},
);
}
return const CircularProgressIndicator();
},
),
);
Dependencies:
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^0.6.3
firebase_messaging: ^0.2.4
Firestore only allows for String keys and dynamic values being, with the exception of Timestamp, core language types. The cloud_firestore plugin keeps document data in an _InternalLinkedHashMap<dynamic, dynamic>. I thought that the Map inside all DocumentSnapshot would be Map<String, dynamic>. How can I work around this? Changing all functions to take Map<dynamic, dynamic> and assume the key is a String is a rather ugly workaround to the problem.
回答1:
I believe this is because the Map returned from Firebase is not a Map<String, dynamic> but instead Map<dynamic, dynamic>.
See https://github.com/flutter/flutter/issues/17417 for a related issue.
回答2:
Use Map<String, dynamic>.from ( mapFromFirestore ). This creates a new Map<String, dynamic> from the contents of mapFromFirestore, throwing an error if it finds a key that isn't a String.
回答3:
Flutter now worked with Map<String,String>
回答4:
I too had this problem and fixed it with --
Map<String, dynamic> var = {'item': 0, 'name': 'John'}
instead of Map unspecified.
Map var = {'item': 0, 'name': 'John'}
来源:https://stackoverflow.com/questions/50159766/flutter-cloud-firestore-mapstring-dynamic-error