Error: The argument type 'String?' can't be assigned to the parameter type 'String'

Viewed 310

I am working on ChatApp trying to save and upload images but I get errors like this Does anyone know the cause of this ? im getting theese type of error i cant fnd any solutons for these..

import 'dart:io';

//Packages
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:file_picker/file_picker.dart';

const String USER_COLLECTION = "Users";

class CloudStorageService {
  final FirebaseStorage _storage = FirebaseStorage.instance;

  CloudStorageService();

  Future<String?> saveUserImageToStorage(
      String _uid, PlatformFile _file) async {
    try {
      Reference _ref =
          _storage.ref().child('images/users/$_uid/profile.${_file.extension}');
      UploadTask _task = _ref.putFile(
        [enter image description here][1]File(_file.path),
      );
      return await _task.then(
        (_result) => _result.ref.getDownloadURL(),
      );
    } catch (e) {
      print(e);
    }
  }

  Future<String?> saveChatImageToStorage(
      String _chatID, String _userID, PlatformFile _file) async {
    try {
      Reference _ref = _storage.ref().child(
          'images/chats/$_chatID/${_userID}_${Timestamp.now().millisecondsSinceEpoch}.${_file.extension}');
      UploadTask _task = _ref.putFile(
        File(_file.path), ----------------> Here is the error
      );
      return await _task.then(
        (_result) => _result.ref.getDownloadURL(),
      );
    } catch (e) {
      print(e);
    }
  }
}
3 Answers

Use the ! operator to convert the string to a non-nullable type

File(_file.path!)

The Dart programming language supports null safety. It means that in Dart nullable and non-nullable types is completely different. E.g.

bool b; // can be true or false
bool? nb; // can be true, false or null, `?` is explicit declaration, that type is nullable

So, String? and String is completely different types. First can be string or null, second can only be a string. And you need to check for null in your case.

String? means it may have value, or it may have null value, but String means it have an appropriate value String type. You can add ! to the last of the data type to sure it's not null.

For example:

String? name = "Jack";
String name2 = name!;
Related