I tried to fetch data from doc Id but then shows this error "The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'." And in this code I tried to fetch from cloud firestore
code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../articlesModel.dart';
class ViewOneArticleScreen extends StatefulWidget {
const ViewOneArticleScreen({Key? key, required this.id}) : super(key: key);
final String id;
@override
State<ViewOneArticleScreen> createState() => _ViewOneArticleScreenState();
}
class _ViewOneArticleScreenState extends State<ViewOneArticleScreen> {
Articles? oneArticle;
bool loading = false;
@override
initState() {
super.initState();
loading = true;
getArticle();
}
Future<void> getArticle() async {
final id = widget.id;
final reference = FirebaseFirestore.instance.doc('articles/$id');
final snapshot = reference.get();
final result =
await snapshot.then((snap) => Articles.fromJson(snap.data()));
print('result is ====> $result');
setState(() {
oneArticle = result;
loading = false;
});
}
@override
Widget build(BuildContext context) {
// print(widget.id);
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: Column(
children: [
Image.network(
oneArticle!.url,
height: 30,
fit: BoxFit.cover,
),
Text(oneArticle!.topic,
style: const TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w500)),
Text(oneArticle!.description,
style: const TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w500)),
],
),
);
}
}
To fetch I used model class. How to resolve this error?
CodePudding user response:
It means that snap.data()
can be null
(it is of type Map<String, dynamic>?
) while doesn't support null
(its parameter is of type Map<String, dynamic>
).
You have 3 solutions:
1. You know that snap.data()
is not null
Then you can use the !
operator:
final result = await snapshot.then((snap) => Articles.fromJson(snap.data()!));
2. Articles.fromJson
actually supports null
Then you can change the parameter type of Articles.fromJson
from Map<String, dynamic>?
to Map<String, dynamic>
.
3. Articles.fromJson
doesn't support null
and snap.data()
can be null
Then you have to support null
yourself in your code:
final result = await snapshot.then((snap) => snap.data() == null ? null : Articles.fromJson(snap.data()!));
You can read more here.