【问题标题】:Problem with [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 的问题未处理的异常:类型'String'不是'index'类型'int'的子类型
【发布时间】:2021-03-22 02:56:23
【问题描述】:

我正在尝试从 API 的 json 文件中获取数据

这是我的反序列化代码:

import 'package:curso_project/Classes/listaTokenLoja.dart';

class LoginInfo {
  String resp;
  int idLogin;
  List<ListaTokenLoja> listaTokenLoja;

  LoginInfo(this.resp, this.idLogin, [this.listaTokenLoja]);

  factory LoginInfo.fromJson(dynamic json) {
    if (json['lista_toquem_loja'] != null) {
      var listaTokenObjJson = json['lista_toquem_loja'] as List;
      List<ListaTokenLoja> _listaToken = listaTokenObjJson
          .map((listaJson) => ListaTokenLoja.fromJson(listaJson))
          .toList();
      return LoginInfo(
          json['resp'] as String, json['id_login'] as int, _listaToken);
    } else {
      return LoginInfo(json['resp'] as String, json['id_login'] as int);
    }
  }

  @override
  String toString() {
    return '{${this.resp}, ${this.idLogin}, ${this.listaTokenLoja}}';
  }
}

这是我的调用 API 函数:

postRequest(login, psd) async {
  final http.Response response = await http.post(
    'http://pdvapi.salaomaster.com.br/logarcli',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({"login": login, "pw": psd, "json_xml": "json"}),
  );
  if (response.statusCode == 200) {
    var json2 = response.body;
    LoginInfo loginInfo = LoginInfo.fromJson(jsonDecode(json2));
    print(loginInfo.idLogin);
    var json = response.body.toString();
    var responseSliced = checkLogin(json);

    return responseSliced;
  } else {
    print(response.statusCode);
    throw Exception('Erro: ${response.statusCode}');
  }
}

这是错误:

I/flutter ( 2696): postando...
I/flutter ( 2696): 1
I/flutter ( 2696): k7f32Sa#
E/flutter ( 2696): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter ( 2696): #0      new LoginInfo.fromJson
package:curso_project/Classes/loginInfo.dart:13
E/flutter ( 2696): #1      postRequest
package:curso_project/api/login.dart:21
E/flutter ( 2696): <asynchronous suspension>
E/flutter ( 2696): #2      LoginPage.build.<anonymous closure>
package:curso_project/main.dart:132
E/flutter ( 2696): #3      _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
E/flutter ( 2696): #4      _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111

我找不到问题出在哪里,因为它指示了一行是 List 而不是 String 我是 flutter 和 dart 的新手,我一直在和他们一起开发一些应用程序

【问题讨论】:

    标签: json api flutter dart mobile


    【解决方案1】:

    解决方案是改变 json 来的方式,它像 String 一样来,所以我使用了 jsonDecode(),它解决了问题

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多