【问题标题】:Dart Enhanced Enum Invalid argument(s): `1` is not one of the supported valuesDart 增强枚举无效参数:`1` 不是支持的值之一
【发布时间】:2022-08-17 21:33:00
【问题描述】:

我有这个枚举 SkillType:

enum SkillType {
  Goal(0),
  Assist(1),
  Plusminus(2),
  Hits(3),
  Penalty(4),
  ShotsOnGoal(5),
  FaceoffsWon(6),
  BlockedShots(7),
  SavePercentage(8);

  const SkillType(this.value);
  final int value;
}

我在与我们来自服务器 api 的响应相匹配的类中使用它:

import \'package:json_annotation/json_annotation.dart\';
import \'../enums/skillType.dart\';

part \'teamskill.g.dart\';

@JsonSerializable()
class TeamSkill {
  final int TeamSkillId;
  final int TeamId;
  final SkillType Skilltype;

  TeamSkill(this.TeamSkillId, this.TeamId, this.Skilltype);

  factory TeamSkill.fromJson(Map<String, dynamic> json) =>
      _$TeamSkillFromJson(json);
  Map<String, dynamic> toJson() => _$TeamSkillToJson(this);
}

当我从我们的服务器获得响应时,SkillType 枚举作为 int 接收,并且我的代码给出了来自 json_annotation 的不支持值的错误:

无效参数:1 不是支持的值之一:目标, 助攻, 正负, 安打, 点球, ShotsOnGoal, FaceoffsWon, BlockedShots, SavePercentage I/flutter (21747): #0 $enumDecode (包:json_annotation/src/enum_helpers.dart:83:5) I/flutter (21747): #1 _$TeamSkillFromJson (包:head_coach_shl/dto/teamskill.g.dart:12:7) I/flutter (21747): #2 新 TeamSkill.fromJson (package:head_coach_shl/dto/teamskill.dart:21:7) I/flutter (21747): #3 API.getSkillTree。 (包:head_coach_shl/api/api.dart:979:57) I/flutter (21747): #4
MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) I/flutter (21747): #5 ListIterator.moveNext (dart:_internal/iterable.dart:342:26) I/flutter (21747): #6 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27) I/flutter (21747): #7
新的 _GrowableList.of (dart:core-patch/growable_array.dart:150:28) I/flutter (21747):#8 新 List.of (dart:core-patch/array_patch.dart:51:28) I/flutter (21747): #9
ListIterable.toList (dart:_internal/iterable.dart:213:44) I/flutter (21747):#10 API.getSkillTree (包:head_coach_shl/api/api.dart:979:70) I/flutter (21747): 我/颤振(21747):#11
_SkillTreeScreenState.loadDetails(包:head_coach_shl/screens/myTeam/skilltree.dart:57:22)

运行 json_annotation 版本 4.6.0 和 json_serializable 版本 6.3.1(和 Dart 2.17.6)。

我一定遗漏了一些关于增强枚举的东西......

    标签: flutter dart enums


    【解决方案1】:

    使用json注解解决...

    import 'package:json_annotation/json_annotation.dart';
    
    enum SkillType {
      @JsonValue(0)
      Goal(0),
      @JsonValue(1)
      Assist(1),
      @JsonValue(2)
      Plusminus(2),
      @JsonValue(3)
      Hits(3),
      @JsonValue(4)
      Penalty(4),
      @JsonValue(5)
      ShotsOnGoal(5),
      @JsonValue(6)
      FaceoffsWon(6),
      @JsonValue(7)
      BlockedShots(7),
      @JsonValue(8)
      SavePercentage(8);
    
      const SkillType(this.value);
      final int value;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 1970-01-01
      • 2021-12-21
      • 2017-10-13
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多