Flutter-未处理的异常:类型'String'不是'index'的'int'类型的子类型 [英] Flutter - Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

查看:466
本文介绍了Flutter-未处理的异常:类型'String'不是'index'的'int'类型的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个api,我可以在控制台中打印api响应。但是,当我收到对模型类的响应时,控制台会显示并显示以下错误

I'm trying to get an api, I can print the api response in the console. However, when I'm receive the respond to my model class, console shows and error like this


E / flutter(9292):[错误:flutter / lib / ui / ui_dart_state.cc(157)]
未处理的异常:类型'String'不是
'index'

E/flutter ( 9292): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

model.dart

class CategoryDishes {
  final String dishId;
  final String dishName;
  final String dishDescription;

  CategoryDishes(
      {this.dishId,
      this.dishName,
      this.dishDescription,});

  factory CategoryDishes.fromJson(Map<String, dynamic> json) {
    return CategoryDishes(
        dishId: json['dish_id'],
        dishName: json['dish_name'],
        dishDescription: json['dish_description'],

  }

  static Resource<List<CategoryDishes>> get all {
    return Resource(
        url: Constants.FOOD_API_URL,
        parse: (response) {
          final result = json.decode(response.body.toString());
          print(response);
          Iterable list = result['category_dishes'];
          return list.map((model) => CategoryDishes.fromJson(model)).toList();
        });
  }
}

web_service.dart

class Resource<T> {
  final String url;
  T Function(Response response) parse;

  Resource({this.url, this.parse});
}

class Webservice {
  Future<T> load<T>(Resource<T> resource) async {
    final response = await http.get(resource.url);
    if (response.statusCode == 200) {
      debugPrint("----D------>" + response.body);
      return resource.parse(response);
    } else {
      throw Exception('Failed to load data!');
    }
  }
}

debugPrint 显示控制台中的api,但也显示上述错误,并且在我创建的视图中未显示api数据。

The debugPrint showing the api in console, but also the above error showing and the api data not showing on my view that I've created.

我做错了什么?

任何建议都会有所帮助。

Any suggestion would be helpful.

推荐答案

API返回JSON数组!尝试如下!

The API returning JSON Array ! Try like below !

    static Resource<List<CategoryDishes>> get all {
            return Resource(
                url: Constants.FOOD_API_URL,
                parse: (response) {
                  final result = json.decode(response.body.toString());
                  print(response);
    //added 0 indexex, so it gets 1st element of JSON Arrays
                  Iterable list = result[0]['table_menu_list'][0]['category_dishes'];
                  return list.map((model) => CategoryDishes.fromJson(model)).toList();
                });
          }

}

这篇关于Flutter-未处理的异常:类型'String'不是'index'的'int'类型的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆