Dhiraj
Dhiraj

Reputation: 49

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

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}"),
              );
            })));
  }
}

Error:

[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>
E/flutter (13226):

Please help me

Upvotes: 1

Views: 873

Answers (1)

Dmitry Rodionov
Dmitry Rodionov

Reputation: 363

As I can see, from your JSON, You don't have field 'data' in the JSON structure. You need to use just:

final jsonDecode=await json.decode(response.body);
for (var i in jsonDecode){
   ModelClass _model=ModelClass.fromJson(i);
   mylist.add(_model);
}

In the GetPostProvider class.

Replace jsonDecode['data'] to jsonDecode. Because in response you receive not a Map<String, dynamic> with key 'data', but List<Map<String, dynamic> (as @julemand101 motion in comment).

Upvotes: 1

Related Questions