Home > Software design >  Tried to fetch document data in firestore subcollection then show this error "Null check operat
Tried to fetch document data in firestore subcollection then show this error "Null check operat

Time:02-01

I tried to fetch document data in firestore subcollection then show this error "Null check operator used on a null value " . I want to fetch one article in user collection for each users.

enter image description here

database screenshot

user table

enter image description here

article subcollection

enter image description here

all articles UI

enter image description here

how to fetch a article when click view button

View button code in All articles UI

ElevatedButton(child: Text('View'),onPressed: () {                                                
 Navigator.of(context).push(MaterialPageRoute(builder: (context) => ViewOneUserArticleScreen(id: data[index].id,)));

view one article code

  Articles? oneArticle;
  bool loading = false;

  @override
  initState() {
    super.initState();
    loading = true;
    getArticle();
  }
  User? user = FirebaseAuth.instance.currentUser;
  UserModel loggedInUser = UserModel();

  Future<void> getArticle() async {

    final id = widget.id;
    final reference = FirebaseFirestore.instance.doc('users/${user?.uid}/articles/$id');
    final snapshot = reference.get();

    final result = await snapshot.then(
        (snap) => snap.data() == null ? null : Articles.fromJson(snap.data()!));

    setState(() {
      oneArticle = result;
      loading = false;
    });
  }

model


class Articles {
  final  String id;
  final  String topic;
  final  String description;
  final  String url;



  Articles({
    required  this.id,
    required this.topic,
    required  this.description,
    required   this.url
  });

  Articles.fromJson(Map<String, dynamic> json)
      : this(
      id: json['id'],
      topic: json['topic']! as String,
      url: json['url']! as String,
      description: json['description']! as String,
     );

  Map<String, Object?> toJson() {
    return {
      'id': id,
      'topic': topic,
      'url': url,
      'description': description,


};
  }



}

new error enter image description here

CodePudding user response:

Your Issue is in your parsing method, change your Articles.fromJson to this:

Articles.fromJson(Map<String, dynamic> json)
  : this(
     id: json['id'] ?? '', // <--- change this
     topic: json['topic'] as String ?? '', // <--- change this
     url: json['url'] as String ?? '', // <--- change this
     description: json['description'] as String ?? '', // <--- change this
  );

in your json, topic, description and url may be null but you used ! on them and that means you are sure that they aren't null but they are. Also your id may be null to but in your object model you set it as required, so you need to provide default value to it or just remove the required before it.

  • Related