【问题标题】:Error: The argument type 'String?' can't be assigned to the parameter type 'String'错误:参数类型“字符串?”不能分配给参数类型“字符串”
【发布时间】:2021-12-20 12:53:04
【问题描述】:

我正在使用 ChatApp 尝试保存和上传图片,但是 我收到这样的错误有人知道这是什么原因吗? 我得到了这些类型的错误,我无法找到任何解决方案。

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);
    }
  }
}

【问题讨论】:

  • PlatformFile.pathstring?。因此,在分配给File之前,您需要检查path 是否为空

标签: firebase flutter firebase-realtime-database google-cloud-firestore google-cloud-functions


【解决方案1】:

The Dart programming language supports null safety。这意味着在 Dart 中,可空类型和不可空类型是完全不同的。例如

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

所以,String?String 是完全不同的类型。 first 可以是字符串或 null,second 只能是字符串。你需要检查你的情况是否为 null。

【讨论】:

  • 非常感谢兄弟
【解决方案2】:

使用 !运算符将字符串转换为不可为空的类型

File(_file.path!)

【讨论】:

  • 非常感谢兄弟
【解决方案3】:

String? 表示它可能有值,或者它可能有null 值,但String 表示它有适当的值字符串类型。 您可以将! 添加到数据类型的最后一个,以确保它不是null

例如:

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

【讨论】:

  • 非常感谢兄弟
猜你喜欢
  • 2021-10-21
  • 2021-10-13
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 2020-04-12
  • 1970-01-01
相关资源
最近更新 更多