I am new to flutter, I have a field called diagnosis that I am trying to fetch from a firestore document that sometimes has a value of " "
or a []
with a single String
value or []
with multiple String
value. But sadly I'm encountering an error type 'List<dynamic>' is not a subtype of type 'String'
. Any help would be highly appreciated. Thank you.
cloud_results.dart
class CloudResults {
final String examinationName;
final String diagnosis;
final String result;
const CloudResults({
required this.examinationName,
this.diagnosis = '',
required this.result,
});
Map<String, dynamic> toJson() {
return {
'examinationName': examinationName,
'diagnosis': diagnosis,
'result': result,
};
}
CloudResults.fromSnapshot(
QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
examinationName = snapshot.data()['examinationName'],
diagnosis = snapshot.data()['diagnosis'],
result = snapshot.data()['result'];
}
results_cloud_storage.dart
class ResultsCloudStorage{
final results = FirebaseFirestore.instance.collection('exam-results');
Stream<Iterable<CloudResults>> allResults({required String patientId}) =>
results.snapshots().map((event) => event.docs
.map((doc) => CloudResults.fromSnapshot(doc))
.where((result) => result.patientId == patientId));
}
exam_record_screen.dart
class _ExamRecordScreenState extends State<ExamRecordScreen> {
late final ResultsCloudStorage _resultsService;
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: _resultsService.allResults(patientId: userId),
builder: (context, snapshot) {
if (snapshot.hasData) {
final allResults = snapshot.data as Iterable<CloudResults>;
return CustomScrollView(slivers: [
SliverList(
...
)
]
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}
),
);
}
}
CodePudding user response:
You can define your diagnostics
variable as a List<String>
, and in your CloudResults.fromSnapshot
, change the method of assigning value to the diagnostics
variable as:
diagnosis = snapshot.data()['diagnosis'] is String? [snapshot.data()['diagnosis']]:snapshot.data()['diagnosis'],
CodePudding user response:
I changed the code for the diagnosis into this.
class CloudResults {
final List<String> diagnosis;
const CloudResults({
this.diagnosis = const [],
and in the CloudResults.fromSnapshot
diagnosis = snapshot.data()['diagnosis'] is String
? [snapshot.data()['diagnosis'] as String]
: (snapshot.data()['diagnosis'] as List<dynamic>)
.map((e) => e as String)
.toList(),