Reputation:
I want to use my response data show in the widget. I post the data to my API then I get the return result.
My response.body is like this:
{
"responses": [
{
"Contents": {
"Images": [
{"url":"https:URL"},
{"url":"https:URL"},
],
"Ages": [
{"age":"33"},
{"age":"34"},
],
"Labels":[
{"label":"game"}
]
}
}
]
}
My question is how to get the "Images", "Ages", and "Labels" details? I want to use these detail and put in my widget. Can I know how to do it?
Upvotes: 0
Views: 1411
Reputation: 2285
It's not mandatory to make full models in Dart for decoding JSON. You can simply do:
// Requires import
import 'dart:convert';
// Do like this
var data = jsonDecode(jsonString);
Now data will automatically act as a map.
For example, if you want to access the label in the JSON example you provided, you can simply do:
data['responses'][0]['Contents']['Labels'][0]['label'].toString();
Coming to the actual part, You need to shape your widgets according to your needs.
Create a Stateless or StatefulWidget whatever suits your needs and start laying out the design.
According to the JSON example that you posted, you need to show a list of images. So, you would probably generate a list of the Widgets based on the URLs and provide the list to perhaps a GridView in your build method.
Check this example I made: DartPad - JSON Widget example
Edit:
I used the exact JSON response you posted. It doesn't give me any errors.
class _MyWidgetState extends State<MyWidget> {
final String mJson = '''
{
"responses": [
{
"Contents": {
"Images": [
{"url":"https:URL"},
{"url":"https:URL"}
],
"Ages": [
{"age":"33"},
{"age":"34"}
],
"Labels":[
{"label":"game"}
]
}
}
]
}
''';
bool _loading = false;
List<String> _infos = [];
Widget _loadingBar() {
return SizedBox.fromSize(
size: Size.fromRadius(30),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('MY APPS'), actions: <Widget>[
_loading
? _loadingBar()
: IconButton(
icon: Icon(Icons.send),
onPressed: () => {
submit(context)
.then((res) => setState(() => _loading = false))
}),
]),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: List.generate(_infos.length, (i) => Text(_infos[i]))),
));
}
Future<void> submit(BuildContext context) async {
setState(() => _loading = true);
await Future.delayed(const Duration(seconds: 3));
var data = jsonDecode(mJson);
print(data);
_infos.add(data['responses'][0].toString());
_infos.add(data['responses'][0]['Contents'].toString());
_infos.add(data['responses'][0]['Contents']['Images'][0]['url'].toString());
_infos.add(data['responses'][0]['Contents']['Ages'][0]['age'].toString());
}
}
Note: The code you posted later shouldn't work as you have declared non-final variables in a StatelessWidget class and also using setState. Also, in your Future submit(BuildContext context) you were supposed to jsonDecode(res) not demoJson. demoJson was not assigned. See the example I posted. I changed it to a stateful widget. I am having no trouble accessing any of the fields in the JSON example you gave. Your JSON example is a bit faulty though, it has extra ',' that might give error while decoding.
Upvotes: 1
Reputation: 3767
Just check the below example that i have made : Follwing is the json file that you provided i have parsed locally.
{
"responses": [{
"Contents": {
"Images": [{
"url": "https:URL"
},
{
"url": "https:URL"
}
],
"Ages": [{
"age": "33"
},
{
"age": "34"
}
],
"Labels": [{
"age": "33"
}
]
}
}]
}
Model class created for the json file:
// To parse this JSON data, do
//
// final response = responseFromJson(jsonString);
import 'dart:convert';
Response responseFromJson(String str) => Response.fromJson(json.decode(str));
String responseToJson(Response data) => json.encode(data.toJson());
class Response {
List<ResponseElement> responses;
Response({
this.responses,
});
factory Response.fromJson(Map<String, dynamic> json) => Response(
responses: List<ResponseElement>.from(json["responses"].map((x) => ResponseElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"responses": List<dynamic>.from(responses.map((x) => x.toJson())),
};
}
class ResponseElement {
Contents contents;
ResponseElement({
this.contents,
});
factory ResponseElement.fromJson(Map<String, dynamic> json) => ResponseElement(
contents: Contents.fromJson(json["Contents"]),
);
Map<String, dynamic> toJson() => {
"Contents": contents.toJson(),
};
}
class Contents {
List<Image1> images;
List<Age> ages;
List<Age> labels;
Contents({
this.images,
this.ages,
this.labels,
});
factory Contents.fromJson(Map<String, dynamic> json) => Contents(
images: List<Image1>.from(json["Images"].map((x) => Image1.fromJson(x))),
ages: List<Age>.from(json["Ages"].map((x) => Age.fromJson(x))),
labels: List<Age>.from(json["Labels"].map((x) => Age.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Images": List<dynamic>.from(images.map((x) => x.toJson())),
"Ages": List<dynamic>.from(ages.map((x) => x.toJson())),
"Labels": List<dynamic>.from(labels.map((x) => x.toJson())),
};
}
class Age {
String age;
Age({
this.age,
});
factory Age.fromJson(Map<String, dynamic> json) => Age(
age: json["age"],
);
Map<String, dynamic> toJson() => {
"age": age,
};
}
class Image1 {
String url;
Image1({
this.url,
});
factory Image1.fromJson(Map<String, dynamic> json) => Image1(
url: json["url"],
);
Map<String, dynamic> toJson() => {
"url": url,
};
}
This is the main UI file where you fetch and show the data, I have show your data in the list view.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/model.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isLoading = false;
List<Age> ages = List();
List<Age> labels = List();
List<Image1> image = List();
// here i have taken the json locally which you posted on stack
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
@override
void initState() {
super.initState();
givenFunction();
}
Future givenFunction() async {
setState(() {
isLoading = true;
});
//http.Response response = await http.post(url, body: json.encode(data));
// you can make the http call above just uncomment is and comment the below line
String jsonString = await loadFromAssets();
// Here you can just replace down your response.body with jsonString
final response = responseFromJson(jsonString);
print(response.responses[0].contents.ages[0].age);
//ages =response.responses[0].contents.
for (int i = 0; i < response.responses[0].contents.ages.length; i++) {
ages.add(response.responses[0].contents.ages[i]);
}
for (int i = 0; i < response.responses[0].contents.images.length; i++) {
image.add(response.responses[0].contents.images[i]);
}
for (int i = 0; i < response.responses[0].contents.labels.length; i++) {
labels.add(response.responses[0].contents.labels[i]);
}
setState(() {
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: isLoading
? CircularProgressIndicator()
: SafeArea(
child: Container(
child: Column(
children: <Widget>[
Container(
width: 400,
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: ages.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100,
height: 100,
child: Card(
elevation: 10,
child: Center(child: Text(ages[index].age)),
),
);
},
),
),
Container(
width: 500,
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: image.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100,
height: 100,
child: Card(
elevation: 10,
child: Center(child: Text(image[index].url)),
),
);
},
),
),
Container(
width: 500,
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: labels.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100,
height: 100,
child: Card(
elevation: 10,
child: Center(child: Text(labels[index].age)),
),
);
},
),
)
],
),
),
)),
);
}
}
void main() {
runApp(HomePage());
}
Just check it and let me know.
Upvotes: 0