【问题标题】:Bloc type 'String' is not a subtype of type 'int' of 'index'Bloc 类型“String”不是“index”的“int”类型的子类型
【发布时间】:2021-08-10 23:00:51
【问题描述】:

美好的一天! 请帮我找出这个小测试应用程序中的错误。

模特/人:

class People extends Equatable {
  final int charId;
 });

  @override
  List<Object> get props => [
        charId,
      ];

  static People fromJson(dynamic json) {
    return People(
      charId: json['char_id'],
      );
  }
}

API客户端:

class APIClient {
  static const baseUrl = '******';
  final http.Client httpClient;

  APIClient({
    required this.httpClient,
  }) : assert(httpClient != null);

  Future<People> fetchPeopleAPI(int id) async {
    final mainUrl = '***';

    final peopleResponse = await this.httpClient.get(Uri.parse(mainUrl));

    if (peopleResponse.statusCode != 200) {
      throw Exception('error getting people with id');
    }
    final peopleJson = jsonDecode(peopleResponse.body);
    return People.fromJson(peopleJson);
  }
}

集团:

class PeopleBloc extends Bloc<PeopleEvent, PeopleState> {
  final PeopleRepo peopleRepo;

  PeopleBloc({
    required this.peopleRepo,
  })   : assert(peopleRepo != null),
        super(PeopleInitialState());

  @override
  Stream<PeopleState> mapEventToState(
    PeopleEvent event,
  ) async* {
    if (event is PeopleRequestedEvent) {
      yield PeopleLoadInProgressState();
      try {
        final People people = await peopleRepo.getPeople(event.id);
        yield PeopleLoadSuccessState(people: people);
      } catch (e) {
        print("error : $e");
        yield PeopleLoadFailureState();
      }
    }
  }
}

正是在 bloc.dart 中,我得到了带有文本“error : type 'String' is not a subtype of type 'int' of 'index'”的异常。请帮忙找出错误。

【问题讨论】:

  • 它告诉你错误在哪一行?
  • 我在 mapEventToState 中通过 print("error: $e") 收到一条消息
  • 如果我使用的不是 char_id,而是字符串名称,评论 char_id 字段我会再次收到一条消息。错误:类型“String”不是“index”类型“int”的子类型
  • 可能是api中的原因?因为当我使用另一个公共 API 时没有任何错误

标签: json flutter bloc


【解决方案1】:

原因可能是这部分:

static People fromJson(dynamic json) {
  return People(
    charId: json['char_id'],
    );
}

由于json 参数是动态的,所以json['char_id'] 的值也是动态的。假设你的 API 返回一个整数为char_id,你可以像这样解析它:

static People fromJson(dynamic json) {
  return People(
    charId: json['char_id'] as int,
    );
}

【讨论】:

  • 如果它不起作用,请查看int.parse(yourString)?
  • 嗯...在哪个地方?
【解决方案2】:

好吧,我错了。我得到的不是单个 json,而是数组。我放了索引,一切都变好了))

final peopleJson = jsonDecode(peopleResponse.body);
return People.fromJson(peopleJson[0]);

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2021-09-08
    • 2020-10-02
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多