Home > other >  Flutter error: The argument type 'DocumentSnapshot<Object?>? can't be assigned to pa
Flutter error: The argument type 'DocumentSnapshot<Object?>? can't be assigned to pa

Time:11-24

I get this Errorcode when I try to run my flutter app and I don't know how to solve it please help:

Error: The argument type 'DocumentSnapshot<Object?>?' can't be assigned to the parameter type 'DocumentSnapshot<Object?>' because 'DocumentSnapshot<Object?>?' is nullable and 'DocumentSnapshot<Object?>' isn't.

  • 'DocumentSnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-3.1.0/lib/cloud_firestore.dart').

  • 'Object' is from 'dart:core'.

     MyUser user = MyUser.fromDocument(snapshot.data);
                                                ^
    

This is my useresRef:

final CollectionReference usersRef =  FirebaseFirestore.instance.collection('users');

And this is the Widget I'm trying to build:

Widget buildProfileHeader(context) {

    final myuser = Provider.of<MyUser>(context);

    return FutureBuilder<DocumentSnapshot>(
      future: usersRef.doc(myuser.id).get(),
      builder: (context, snapshot) {
        if(!snapshot.hasData){
          return circularProgress();
        }
        MyUser user = MyUser.fromDocument(snapshot.data);

        return Row(...)

This is the MyUser Factory:

import 'package:cloud_firestore/cloud_firestore.dart';

class MyUser{
  final String id;
  final String email;
  final String photoUrl;
  final String displayName;
  final String username;

  MyUser({
    required this.id,
    required this.email,
    required this.photoUrl,
    required this.displayName,
    required this.username,
  });

  factory MyUser.fromDocument(DocumentSnapshot doc){
    return MyUser(
        id: doc['id'].toString(),
        username: doc['username'].toString(),
        email: doc['email'].toString(),
        photoUrl: doc['photoUrl'].toString(),
        displayName: doc['displayName'].toString(),
    );
  }

I don't understand how i could fix that issue. I tried using snapshot.data.data(), however while it fixed my current error it gave me the new error message:

error: The method 'data' can't be unconditionally invoked because the receiver can be 'null'. (unchecked_use_of_nullable_value at [flutter_app] lib\pages\profile_screen.dart:58)

CodePudding user response:

Yuu just need to use :

MyUser user = MyUser.fromDocument(snapshot.data!);

because at this point in your code, even if you tested snapshot.hasData, dart is telling you that data could be null... But you already handled this case, so it's ok to add a !

  • Related