You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自定义Site类的copyWith方法提示id等命名参数未定义错误

报错原因
  • 你在copyWith方法中调用的是类默认的Site(this.id,this.name,this.address,this.city)构造函数,该构造定义的是位置参数,调用时不需要写参数名、按顺序传值即可,但你代码里用了id: xx这种命名参数的传参写法,编译器找不到对应命名参数就抛出了报错。
  • 额外语法错误:代码中所有Map<"String", "dynamic">的泛型参数加了多余的双引号,泛型为类型声明不需要加引号,正确写法为Map<String, dynamic>。
  • 隐藏逻辑问题:toMap方法错误给ville字段赋值了name属性,fromMapObject构造没有处理address字段赋值,都会导致后续业务逻辑出问题。
修复方案

两种方案可选,推荐第一种改动最小:

方案1:copyWith调用已有的命名构造

你已经定义了Site.JSON命名构造支持命名参数传值,直接修改copyWith内的构造调用即可:

Site copyWith({
  String? id,
  String? name,
  String? address,
  String? city,
}) =>
    Site.JSON(
      id : id ?? this.id,
      name : name ?? this.name,
      address : address ?? this.address,
      city : city ?? this.city,
    );

同时把代码中所有Map<"String", "dynamic">的双引号删除,修正泛型语法。

方案2:修改默认构造为命名参数

如果要保留调用默认构造的写法,修改默认构造的声明即可:

Site({
  required this.id,
  required this.name,
  required this.address,
  required this.city,
});
完整修复后代码
import 'package:json_annotation/json_annotation.dart';

class Site {
  Site(this.id,this.name,this.address,this.city);
  String id;
  String name;
  String address;
  String city;

  Site.JSON({
    required this.id,
    required this.name,
    required this.address,
    required this.city
  });

  Map<String, dynamic> toMap(){
    var map = <String, dynamic>{};
    map['id'] = id;
    map['name'] = name;
    map['address'] = address;
    map['city'] = city;
    // 如果你确实需要ville字段再保留下面这行,否则可以删除
    // map['ville'] = name;
    return map;
  }
  Site copyWith({
    String? id,
    String? name,
    String? address,
    String? city,
  }) =>
      Site.JSON(
        id : id ?? this.id,
        name : name ?? this.name,
        address : address ?? this.address,
        city : city ?? this.city,
      );
  // 从Map对象提取Site实例
  Site.fromMapObject(Map<String, dynamic> map){
    this.id = map['id'];
    this.name = map['name'];
    this.address = map['address'];
    this.city = map['city'];
  }

  // toString方法
  @override
  String toString(){
    return  ' / ' + this.name + ' / ' + this.city;
  }
  Map<String, dynamic> toJson() => {
    "id": id,
    "city": city,
    "name": name,
    "address":address
  };
  factory Site.fromJson(Map<String, dynamic> json) => Site.JSON(
    id: json["id"],
    city: json["city"],
    name: json["name"],
    address: json["address"],
  );
}

如果你使用的是非空安全的旧版Dart,删除代码中的?和required关键字即可正常运行

内容的提问来源于stack exchange,提问作者YA TUBE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:30:04