Home > Software design >  Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index

Time:09-22

I convert my json to class, and wanna use get.dio() method. I get the error "Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'. How can I solve it?

That's my class.

 class Word {
Word({
String? kelime,
String? anlami,
}) {
_kelime = kelime;
_anlami = anlami;
}

Word.fromJson(dynamic json) {
_kelime = json['kelime'];
_anlami = json['anlami'];
}
String? _kelime;
String? _anlami;
Word copyWith({
  String? kelime,
  String? anlami,
 }) =>
  Word(
    kelime: kelime ?? _kelime,
    anlami: anlami ?? _anlami,
  );
String? get kelime => _kelime;
String? get anlami => _anlami;

Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['kelime'] = _kelime;
map['anlami'] = _anlami;
return map;

} }

and these are my getting codes.

Word wordData = Word();

@override
void initState() {
 super.initState();
    getWordData();
    setState(() {});
 });
}

getWordData() async {
  var dio = Dio();
  var responce = await dio.get("https://raw.githubusercontent.com/saturu/turkish_dictionary/main/4_letter.json");
  wordData = Word.fromJson(responce.data);
  print(wordData);
}

CodePudding user response:

The api returns a list of words, List. u can modify the code as follows

List<Word> wordData = [];

@override
void initState() {
 super.initState();
    getWordData();
    setState(() {});
 });
}

getWordData() async {
  final dio = Dio();
  final response = await dio.get("https://raw.githubusercontent.com/saturu/turkish_dictionary/main/4_letter.json");
  wordData = List.from(response).map((word)=> Word.fromJson(word)).toList();
}

CodePudding user response:

The URL is returning a list of maps, and you are trying to assign the list to the model Word.

I think you need to update the widget as

List<Word> wordData = [];

@override
void initState() {
 super.initState();
    getWordData();
 });
}

getWordData() async {
  var dio = Dio();
  var responce = await dio.get("https://raw.githubusercontent.com/saturu/turkish_dictionary/main/4_letter.json");
  wordData = jsonDecode(responce.data).map((e)=> Word.fromJson(e)).toList();
    setState(() {});
}

CodePudding user response:

import 'dart:convert'; //import this

List<Word> wordData = []; //declare


getWordData() async {
  var dio = Dio();
  var responce = await dio.get("https://raw.githubusercontent.com/saturu/turkish_dictionary/main/4_letter.json");
  wordData =(json.decode(response.body) as List).map((val) => Word.fromJson(val)).toList();
  print(wordData);
}
  • Related