参数类型“对象?” 无法分配给参数类型“Map <String,dynamic>”

Dav*_*ata 2 dart firebase flutter

我正在尝试使用小组件从 Firestore 中的文档中检索数据。我过去用过这个,我想是用不同版本的 Dart 或 flutter,而且它有效。现在,当我使用参数类型“对象?”时,显示以下错误 (doc.data()) 无法分配给参数类型“Map <String,dynamic>”

这是代码

DriverProvider driverProvider;

void getDriverInfo() {
    Stream<DocumentSnapshot> driverStream =
        driverProvider!.getbyIdStream(FirebaseAuth.instance.currentUser!.uid);
    driverStream.listen((DocumentSnapshot doc) {
      driver = Driver.fromJson(doc.data());
    });
  }

Run Code Online (Sandbox Code Playgroud)

这里是driverProvider!来自

import 'package:brokerdrivers/models/user-models.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DriverProvider {
  CollectionReference? _ref;

  DriverProvider() {
    _ref = FirebaseFirestore.instance.collection('Drivers');
  }

  Future? create(Driver driver) {
    String? errorMessage;

    try {
      return _ref!.doc(driver.id).set(driver.toJson());
    } catch (e) {
      print(e);
      errorMessage = e.toString();
      return Future.error(errorMessage);
    }
  }

  Stream<DocumentSnapshot> getbyIdStream(String id) {
    return _ref!.doc(id).snapshots(includeMetadataChanges: true);
  }
}



Run Code Online (Sandbox Code Playgroud)

这就是getbyIdStream来自


  Stream<DocumentSnapshot> getbyIdStream(String id) {
    return _ref!.doc(id).snapshots(includeMetadataChanges: true);
  } 

Run Code Online (Sandbox Code Playgroud)

这是我的 Json 模型

import 'dart:convert';

Driver driverFromJson(String str) => Driver.fromJson(json.decode(str));

String driverToJson(Driver data) => json.encode(data.toJson());

class Driver {
  Driver({
    required this.id,
    required this.username,
    required this.email,
    required this.truck,
    required this.carrier,
    required this.insurance,
  });

  String id;
  String username;
  String email;
  String truck;
  String carrier;
  String insurance;

  factory Driver.fromJson(Map<String, dynamic> json) => Driver(
        id: json["id"],
        username: json["username"],
        email: json["email"],
        truck: json["truck"],
        carrier: json["carrier"],
        insurance: json["insurance"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "username": username,
        "email": email,
        "truck": truck,
        "carrier": carrier,
        "insurance": insurance,
      };
}


Run Code Online (Sandbox Code Playgroud)

这是有错误的行

driver = Driver.fromJson(doc.data());
Run Code Online (Sandbox Code Playgroud)

感谢大家的帮助。

Vic*_*ele 12

此错误是由于 API 的新更改造成的cloud_firestore。您需要指定从您的数据中获取的数据类型DocumentSnapshot

更新这一行:

    driver = Driver.fromJson(doc.data());
Run Code Online (Sandbox Code Playgroud)

对此:

    driver = Driver.fromJson(doc.data() as Map<String, dynamic>);
Run Code Online (Sandbox Code Playgroud)

查看迁移到 cloud_firestore 2.0.0的指南。