I am able to fetch the JSON data successfully, but not able to fetch the fields of JSON data and build a list in flutter. If json starts with [] it works fine but this type of json is not working properly. I can see response but I think I am wrong at Mapping data with list. I am new to this flutter and JSON learning, I think I am wrong at this point only
main.dart
import 'package:myapp/screens/character_list.dart';
import 'package:flutter/material.dart';
void main()
{
runApp(MyApp());
}
class MyApp extends StatelessWidget
{
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Breaking Bad App",
theme: ThemeData(primarySwatch: Colors.blue),
home: CharacterList(),
);
}
}
character.dart
class Character
{
String category;
Character.fromJson(Map json) : category = json['category'];
Map toJson() {
return {'category': category};
}
}
character_list.dart
import 'dart:convert';
import 'package:myapp/data/character_api.dart';
import 'package:myapp/model/character.dart';
import 'package:flutter/material.dart';
class CharacterList extends StatefulWidget
{
CharacterList({Key key}) : super(key: key);
@override
_CharacterListState createState() => _CharacterListState();
}
class _CharacterListState extends State<CharacterList>
{
List<Character> characterList = new List<Character>();
void getCharactersfromApi() async
{
CharacterApi.getCharacters().then((response)
{
setState(()
{
Iterable list = json.decode(response.body);
characterList = list.map((model) => Character.fromJson(model)).toList();
});
});
}
@override
void initState()
{
super.initState();
getCharactersfromApi();
}
@override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
title: Text("Breaking Bad Characters"),
),
body: Container(
child: ListView.builder(
itemCount: characterList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(characterList[index].category),
);
}),
));
}
}
character_api.dart
import 'dart:async';
import 'package:http/http.dart' as http;
class CharacterApi {
static Future getCharacters() {
return http
.get(Uri.parse('API URL'));
}
}
json structure is as follows:
{
"urlset": {
"item": [{
"category": ""
}, {
"category": "All-in-One PC"
}, {
"category": "Apparels & Accessories"
}, {
"category": "Art & Craft"
}, {
"category": "Audio Speaker & Accessories"
}
]
}
}
CodePudding user response:
If your JSON starts with [] (square brackets), it means your JSON has a list of objects, but if it has these {} curly brackets around it, that means the data is an object not a list or you can say it is a single object which can not be used as a list.
CodePudding user response:
I think what you are missing is stepping into your correct json property. Something like: characterList = json.decode(response.body)["urlset"]["item"];