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

Flutter类型转换错误求助:'String'不是'index'的'int'子类型

Flutter应用异常排查:String不是int的index子类型

错误信息

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

错误栈

E/flutter (13226): #0      GetPostProvider.getAllPost (package:apiflutter/provider/postProvider.dart:51:7)
E/flutter (13226): <asynchronous suspension>
E/flutter (13226): #1      GetPostProvider.getMyData (package:apiflutter/provider/postProvider.dart:26:18)
E/flutter (13226): <asynchronous suspension>

相关代码

Model代码

class ModelClass {
  String? userId;
  String? id;
  String? title;
  String? body;
  ModelClass({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  Map<String, dynamic> toJson() {
    return {'userId': userId, 'id': id, 'title': title, 'body': body};
  }

  factory ModelClass.fromJson(Map<String, dynamic> data) {
    final userId = data['userId'];
    final id = data['id'];
    final title = data['title'];
    final body = data['body'];
    return ModelClass(id: id, userId: userId, title: title, body: body);
  }
}

Repo代码

class GetPostProvider with ChangeNotifier {
  bool isLoading = false;

  List<ModelClass> modelclass = [];

  getMyData() async {
    isLoading = true;
    modelclass = await getAllPost();
    isLoading = false;
    notifyListeners();
  }

  Future<List<ModelClass>> getAllPost() async {
    final response =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
    List<ModelClass> mylist = [];

    try {
      if (response.statusCode == 200) {
        final jsonDecode = await json.decode(response.body);
        for (var i in jsonDecode['data']) {
          ModelClass _model = ModelClass.fromJson(i);
          mylist.add(_model);
        }
        return mylist;
      } else {
        return mylist;
      }
    } catch (e) {
      throw e.toString();
    }
  }
}

UI代码

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    // TODO: implement initState
    final provider = Provider.of<GetPostProvider>(context, listen: false);
    provider.getMyData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<GetPostProvider>(context);

    return Scaffold(
        appBar: AppBar(
          title: const Text('User Id'),
        ),
        body: ListView.builder(
            itemCount: provider.modelclass.length,
            itemBuilder: ((context, index) {
              return ListTile(
                title: Text("${provider.modelclass[index].body}"),
              );
            })));
  }
}

问题原因及修复方案

核心问题

调用https://jsonplaceholder.typicode.com/posts接口返回的是直接的JSON数组,而非包含data字段的JSON对象。代码中jsonDecode['data']试图用字符串'data'作为索引访问数组,而数组的索引必须是整数类型,因此触发类型转换异常。

修复步骤

1. 修正Repo的JSON解析逻辑

修改getAllPost方法,直接遍历解析后的数组,无需访问data字段:

Future<List<ModelClass>> getAllPost() async {
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  List<ModelClass> mylist = [];

  try {
    if (response.statusCode == 200) {
      // 直接将解析结果转为List类型
      final List jsonData = json.decode(response.body);
      for (var item in jsonData) {
        ModelClass _model = ModelClass.fromJson(item);
        mylist.add(_model);
      }
      return mylist;
    } else {
      return mylist;
    }
  } catch (e) {
    throw e.toString();
  }
}

同时移除json.decode前的await,因为该方法是同步操作,不需要异步等待。

2. (可选)匹配Model与接口数据类型

接口返回的userId和id是整数类型,将Model中对应字段改为int?,避免隐式类型转换:

class ModelClass {
  int? userId;
  int? id;
  String? title;
  String? body;
  ModelClass({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  Map<String, dynamic> toJson() {
    return {'userId': userId, 'id': id, 'title': title, 'body': body};
  }

  factory ModelClass.fromJson(Map<String, dynamic> data) {
    final userId = data['userId'] as int?;
    final id = data['id'] as int?;
    final title = data['title'] as String?;
    final body = data['body'] as String?;
    return ModelClass(id: id, userId: userId, title: title, body: body);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:09:10