I am trying to convert a list of type Response to a json, but I am not getting it.
This is my list of objects:
I want a json like this:
{
"preguntas": [
{
"id": "7d0e0584-3049-4814-b127-0faa02b455b4",
"encuesta": null,
"orden": 1,
"descripcion": "Dificultad para respirar de moderada a grave (no puede decir frases completas)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
},
{
"id": "9809e985-2d1f-4f79-a5b9-da6731e14012",
"encuesta": null,
"orden": 2,
"descripcion": "Fiebre o sentirse afiebrados (escalofríos, sudoración)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
}
]
}
I'm new to Flutter, please if someone help me, I really appreciate it.
You can can copy paste run full code below
You can use full model class definition Payload below and parse with payloadToJson
This example code create Payload object with your json string and convert it back to json string
code snippet
String payloadToJson(Payload data) => json.encode(data.toJson());
...
String str = payloadToJson(payload);
print(str);
output
{"preguntas":[{"id":"7d0e0584-3049-4814-b127-0faa02b455b4","encuesta":null,"orden":1,"descripcion":"Dificultad para respirar de moderada a grave (no puede decir frases completas)","respuestas":[],"obligatoria":true,"estado":false,"fechaCreacion":null,"responsableCreacion":null,"fechaModificacion":null,"responsableModificacion":null},{"id":"9809e985-2d1f-4f79-a5b9-da6731e14012","encuesta":null,"orden":2,"descripcion":"Fiebre o sentirse afiebrados (escalofríos, sudoración)","respuestas":[],"obligatoria":true,"estado":false,"fechaCreacion":null,"responsableCreacion":null,"fechaModificacion":null,"responsableModificacion":null}]}
full code
import 'package:flutter/material.dart';
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Pregunta> preguntas;
Payload({
this.preguntas,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
preguntas: List<Pregunta>.from(json["preguntas"].map((x) => Pregunta.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"preguntas": List<dynamic>.from(preguntas.map((x) => x.toJson())),
};
}
class Pregunta {
String id;
dynamic encuesta;
int orden;
String descripcion;
List<dynamic> respuestas;
bool obligatoria;
bool estado;
dynamic fechaCreacion;
dynamic responsableCreacion;
dynamic fechaModificacion;
dynamic responsableModificacion;
Pregunta({
this.id,
this.encuesta,
this.orden,
this.descripcion,
this.respuestas,
this.obligatoria,
this.estado,
this.fechaCreacion,
this.responsableCreacion,
this.fechaModificacion,
this.responsableModificacion,
});
factory Pregunta.fromJson(Map<String, dynamic> json) => Pregunta(
id: json["id"],
encuesta: json["encuesta"],
orden: json["orden"],
descripcion: json["descripcion"],
respuestas: List<dynamic>.from(json["respuestas"].map((x) => x)),
obligatoria: json["obligatoria"],
estado: json["estado"],
fechaCreacion: json["fechaCreacion"],
responsableCreacion: json["responsableCreacion"],
fechaModificacion: json["fechaModificacion"],
responsableModificacion: json["responsableModificacion"],
);
Map<String, dynamic> toJson() => {
"id": id,
"encuesta": encuesta,
"orden": orden,
"descripcion": descripcion,
"respuestas": List<dynamic>.from(respuestas.map((x) => x)),
"obligatoria": obligatoria,
"estado": estado,
"fechaCreacion": fechaCreacion,
"responsableCreacion": responsableCreacion,
"fechaModificacion": fechaModificacion,
"responsableModificacion": responsableModificacion,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
String jsonString = '''
{
"preguntas": [
{
"id": "7d0e0584-3049-4814-b127-0faa02b455b4",
"encuesta": null,
"orden": 1,
"descripcion": "Dificultad para respirar de moderada a grave (no puede decir frases completas)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
},
{
"id": "9809e985-2d1f-4f79-a5b9-da6731e14012",
"encuesta": null,
"orden": 2,
"descripcion": "Fiebre o sentirse afiebrados (escalofríos, sudoración)",
"respuestas": [],
"obligatoria": true,
"estado": false,
"fechaCreacion": null,
"responsableCreacion": null,
"fechaModificacion": null,
"responsableModificacion": null
}
]
}
''';
Payload payload = payloadFromJson(jsonString);
String str = payloadToJson(payload);
print(str);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Maybe it can works; I can create Model class for example. You should add toJson() Function to your Class.
class Model{
String id = "7d0e0584-3049-4814-b127-0faa02b455b4";
String encuesta = "null";
int orden = 1;
String description = "Dificultad para respirar de moderada a grave (no puede...)";
bool obligatoria = true;
//Model(bla bla bla....)
Model();
toJson(){
return {
"id":id,
"encuesta":encuesta,
"orden":orden,
"description":description,
"obligatoria":obligatoria
};
}
}
void main() {
Map<String,List<dynamic>> jsonMap = new Map();
List<dynamic> list = new List();
for(int i = 0 ; i < 3;i++){
Model model = new Model();
list.add(model.toJson());
}
jsonMap['preguntas'] = list;
print(jsonMap);
}
Result (Print):
{
preguntas: [
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
},
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
},
{
id: 7d0e0584-3049-4814-b127-0faa02b455b4,
encuesta: null,
orden: 1,
description: Dificultadpararespirardemoderadaagrave(nopuede...),
obligatoria: true
}
]
}
Related
I have tried moving the flutter toggle from setState to bloc. I cannot get the toggle buttons to toggle.
The BlocEvent:
abstract class ToggleSizeEvent extends Equatable {
const ToggleSizeEvent();
#override
List<Object?> get props => [];
}
class SelectSize extends ToggleSizeEvent {
const SelectSize({
required this.idSelected,
});
final int idSelected;
#override
List<Object?> get props => [idSelected];
}
The State:
enum ToggleSizeStatus { initial, success, error, loading, selected }
extension ToggleSizeStatusX on ToggleSizeStatus {
bool get isInitial => this == ToggleSizeStatus.initial;
bool get isSuccess => this == ToggleSizeStatus.success;
bool get isError => this == ToggleSizeStatus.error;
bool get isLoading => this == ToggleSizeStatus.loading;
bool get isSelected => this == ToggleSizeStatus.selected;
}
class ToggleSizeState extends Equatable {
ToggleSizeState(
{String size = '',
// this.product,
this.status = ToggleSizeStatus.initial,
List<bool>? sizeSelection,
int idSelected = 0,
this.index = 0})
// : sizeSelection = List.generate(product.size!.length, (index) => false),
: idSelected = idSelected,
size = size;
final List<bool> sizeSelection = [false, false, false, false];
// final ProductModel product;
final ToggleSizeStatus status;
final int idSelected;
final String size;
final int index;
#override
List<Object> get props => [status, sizeSelection, idSelected, size];
ToggleSizeState copyWith({
List<bool>? sizeSelection,
ToggleSizeStatus? status,
int? idSelected,
String? size,
int? index,
}) {
return ToggleSizeState(
// product: product,
sizeSelection: sizeSelection ?? this.sizeSelection,
status: status ?? this.status,
idSelected: idSelected ?? this.idSelected,
size: size ?? this.size,
index: index ?? this.index);
}
}
The bloc:
part 'toggle_size_event.dart';
part 'toggle_size_state.dart';
class ToggleSizeBloc extends Bloc<ToggleSizeEvent, ToggleSizeState> {
final ProductModel product;
ToggleSizeBloc({required this.product})
: super(ToggleSizeState(product: product)) {
on<SelectSize>(_mapSelectSizeEventToState);
}
int newIndex = 0;
void _mapSelectSizeEventToState(
SelectSize event, Emitter<ToggleSizeState> emit) async {
for (int index = 0; index < state.sizeSelection.length; index++) {
if (index == newIndex) {
state.sizeSelection[index] = !state.sizeSelection[index];
} else {
state.sizeSelection[index] = false;
}
}
emit(state.copyWith(
status: ToggleSizeStatus.selected,
idSelected: event.idSelected,
sizeSelection: state.sizeSelection));
}
}
For the UI:
class ProductSize extends StatefulWidget {
final ProductModel product;
const ProductSize({super.key, required this.product});
#override
State<ProductSize> createState() => _ProductSizeState();
}
class _ProductSizeState extends State<ProductSize> {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Column(
children: [
const Text('Please select size'),
BlocProvider(
create: (context) => ToggleSizeBloc(product: widget.product),
child: BlocBuilder<ToggleSizeBloc, ToggleSizeState>(
builder: (context, state) {
debugPrint('ToggleSize Page ${state.sizeSelection}');
return ToggleButtons(
selectedColor: Colors.white,
color: pureBlack,
fillColor: thistle,
splashColor: lilac,
highlightColor: lilac,
textStyle: const TextStyle(fontWeight: FontWeight.bold),
renderBorder: true,
borderColor: lilac,
borderWidth: 1.5,
borderRadius: BorderRadius.circular(10),
selectedBorderColor: lilac,
isSelected: state.sizeSelection,
onPressed: (int newIndex) {
context.read<ToggleSizeBloc>().add(SelectSize(
idSelected: widget.product.id!,
));
},
children: [
for (var item in widget.product.size!)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(item, style: const TextStyle(fontSize: 18)),
),
],
);
},
),
),
],
),
);
}
}
Please i have been on this for a while. Any help would be appreciated. I am trying to get the toggle button to toggle on selection. Am i doing the for loop in a wrong way?
class ProductModel {
const ProductModel({
this.name,
this.size,
this.imgsUrl,
this.id,
this.description,
this.owner,
this.price,
});
final String? name;
final String? description;
final String? price;
final int? id;
final String? owner;
final List<String>? imgsUrl;
final List<String>? size;
factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
name: json["name"],
price: json["price"],
imgsUrl: List<String>.from(json["imgs_url"].map((x) => x)),
size: List<String>.from(json["size"].map((x) => x)),
id: json["id"],
description: json["description"],
owner: json["owner"],
);
Map<String, dynamic> toJson() => {
"name": name,
"imgs_url": List<dynamic>.from(imgsUrl!.map((x) => x)),
"size": List<dynamic>.from(size!.map((x) => x)),
"id": id,
"description": description,
"owner": owner,
"price": price,
};
static const empty = ProductModel(
description: '',
price: '',
id: 0,
imgsUrl: [],
owner: '',
name: '',
size: [],
);
}
For the sample data to reproduce the issu:
{
"id": 2,
"name": "Roma",
"owner": "pythonGO",
"price": "450485.99",
"description": "Mixed Colored",
"imgs_url": [
"http://1111.com/product-images/yadrafektxqvrckoymjoqktdhwxpjnulqqymattavpvqdfzsnpsdzcxdbhmurxnfHeels.png"
],
"imgs_name": [
"product-images/yadrafektxqvrckoymjoqktdhwxpjnulqqymattavpvqdfzsnpsdzcxdbhmurxnfHeels.png"
],
"size": [
"45",
"46",
"47",
"48"
],
"is_promoted": {
"Bool": false,
"Valid": true
},
"is_trending": {
"Bool": false,
"Valid": true
},
"is_mens": {
"Bool": false,
"Valid": true
},
"is_womens": {
"Bool": false,
"Valid": true
},
"is_kids": {
"Bool": false,
"Valid": true
},
"created_at": "2022-10-26T08:27:22.600809Z",
}
eg: details about the questions ..........................................................................
When I want to fetch multiple objects from an array showing status code 403(Failed to load post).and API having a header key I have implemented it also. but showing failed to load post status code 403.
{
"status": 1,
"msg": "7 banners found",
"data": [
{
"id": "14",
"image": "https://www.sofikart.com/admin/upload/app_banner/1635945056.jpeg",
"cat_id": "4",
"product_id": "81",
"url": null,
"status": "Active",
"ordering": "0",
"updated": "2021-11-03 06:10:56"
},
{
"id": "7",
"image": "https://www.sofikart.com/admin/upload/app_banner/1642082634.jpeg",
"cat_id": "4",
"product_id": "111",
"url": null,
"status": "Active",
"ordering": "1",
"updated": "2021-10-28 04:53:26"
}
]
}
controller
-----------
import 'dart:io';
import 'package:fm_sidharth/model/post.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
final String url = 'https://www.sofikart.com/MobileApi/banners';
Future<List<Post>> fetchPost() async {
final response = await http.get(
url, headers: {HttpHeaders.authorizationHeader: 'SOFIKART-*2021#',},);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final result = json.decode(response.body);
List<Post> posts =
result.map<Post>((model) => new Post.fromJson(model)).toList();
return posts;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<String> saveNetworkImageToPhoto(String url, String title,
{bool useCache: true}) async {
var data = await getNetworkImageData(url, useCache: useCache);
var filePath = await ImagePickerSaver.saveFile(fileData: data, title: title);
return filePath;
}
class ImagePickerSaver {
static saveFile({fileData, String title}) {}
}
getNetworkImageData(String url, {booluseCache, bool
useCache}) {
}
model
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Post welcomeFromJson(String str) => Post.fromJson(json.decode(str));
String welcomeToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
this.status,
this.msg,
this.data,
});
int status;
String msg;
List<Datum> data;
factory Post.fromJson(Map<String, dynamic> json) => Post(
status: json["status"],
msg: json["msg"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
String get catId => null;
get image => null;
Map<String, dynamic> toJson() => {
"status": status,
"msg": msg,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.id,
this.image,
this.catId,
this.productId,
this.url,
this.status,
this.ordering,
this.updated,
});
String id;
String image;
String catId;
String productId;
dynamic url;
String status;
String ordering;
DateTime updated;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
image: json["image"],
catId: json["cat_id"],
productId: json["product_id"],
url: json["url"],
status: json["status"],
ordering: json["ordering"],
updated: DateTime.parse(json["updated"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"image": image,
"cat_id": catId,
"product_id": productId,
"url": url,
"status": status,
"ordering": ordering,
"updated": updated.toIso8601String(),
};
}
home
import 'package:flutter/material.dart';
import 'package:fm_sidharth/Controller/postController.dart';
import 'package:fm_sidharth/model/post.dart';
import 'package:fm_sidharth/page/postdetails.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> posts;
_HomePageState() {
posts = fetchPost();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PostDetails(snapshot.data[index])),
);
},
child: Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data[index].catId,
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: 10,
),
FadeInImage.assetNetwork(
image: snapshot.data[index].image,
placeholder: 'assets/images/noimage.png',
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.share),
onPressed: () {
},
),
IconButton(
icon: Icon(Icons.save),
onPressed: () {
saveNetworkImageToPhoto(
snapshot.data[index].image,snapshot.data[index].catId).then((value){
});
},
),
],
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
},
),
);
}
}
I have this error too some times, I think this about restrict that google set on you country. please use a proxy. I hope my answer helping to you :)
This is the JSON Response I'm getting. I want to Parse the text which says "url" (With. I want to Get this Text)
{
"data": [
{
"id": 1,
"attributes": {
"Title": "My Story",
"Story": "My story is about my life",
"Image": {
"data": {
"id": 1,
"attributes": {
"name": "lifeImage.jpeg",
"alternativeText": "lifeImage.jpeg",
"caption": "lifeImage.jpeg",
"url": "/uploads/lifeImage_0e9293ee8d.jpeg", <-- I want to Get this Text
"previewUrl": null,
"provider": "local"
}
}
}
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 3
}
}
}
I easily parsed the Title, Story with the Below Dart File.
But I'm not sure how can I parse the URL text (One with arrow marks says "<-- I want to Get this Text"). Since it's nested one I don't know how to do that. Please help me with this. Thanks
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'StoryPage.dart';
void main() => runApp(App());
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Stories',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Homepage(),
);
}
}
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
Future<List<Story>> _getStories() async {
var response = await http.get(Uri.parse(
'https://exampleapi.com/api/stories/?populate=Image'));
if (response.statusCode == 200) {
Map responseData = jsonDecode(response.body);
List StoriesList = responseData["data"];
List<Story> stories = [];
for (var storyMap in StoriesList) {
stories.add(Story.fromJson(storyMap["attributes"]));
}
return stories;
} else {
throw Exception('Failed to load stories');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My Stories'),
),
body: Container(
child: FutureBuilder(
future: _getStories(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[index].title,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new StoryPage(
snapshot.data[index],
title: snapshot.data[index].title,
body: snapshot.data[index].body,
)));
},
);
},
);
}
},
),
),
);
}
}
class Story {
final String title;
final String body;
Story({required this.title, required this.body});
factory Story.fromJson(Map<String, dynamic> json) {
return Story(
title: json['Title'],
body: json['Story'],
);
}
}
You can simply parse them like this:
final url = json['image']?['data']?['attributes']?['url'];
here we're using question marks (?) in between, because we're not sure that each element is not null, for example, the data under image may be null, so by using question marks, we're staying safe from null exceptions.
I took #Adnan approach and modified it little.
final ImageURL = json['Image']?['data']?['attributes']?['url'] ?? ''
Thanks to GitHub Co-Pilot.
I suggest using this website to generate dart or any other language object from json.
you just need to covert it to null safety.
here a example:
class AnswerResponse {
AnswerResponse({
required this.id,
required this.description,
required this.isAccepted,
required this.isMine,
required this.media,
required this.caseId,
required this.voteUp,
required this.voteDown,
required this.votes,
required this.user,
required this.comment,
required this.createdAt,
});
factory AnswerResponse.fromJson(final String str) => AnswerResponse.fromMap(json.decode(str));
factory AnswerResponse.fromMap(final Map<String, dynamic> json) => AnswerResponse(
id: json["id"],
description: json["description"],
isAccepted: json["isAccepted"],
isMine: json["isMine"],
media: json["media"] == null ? null : List<MediaResponse>.from(json["media"].map((final dynamic x) => MediaResponse.fromMap(x))),
caseId: json["caseId"],
voteUp: json["voteUp"],
voteDown: json["voteDown"],
votes: json["votes"],
user: json["user"] == null ? null : ProfileResponse.fromMap(json["user"]),
comment: json["comment"] == null ? null : List<CommentResponse>.from(json["comment"].map((final dynamic x) => CommentResponse.fromMap(x))),
createdAt: json["createdAt"],
);
final int? id;
final int? caseId;
final int? votes;
final bool? isAccepted;
final bool? isMine;
final bool? voteUp;
final bool? voteDown;
final String? description;
final String? createdAt;
final ProfileResponse? user;
final List<MediaResponse>? media;
final List<CommentResponse>? comment;
}
and to convert json string to dart object:
var data = AnswerResponse.fromMap(jsonString)
The error usually occures when I scroll to the end of a list of post.
Here is the code for fetching posts from the Word press api
Future<List<dynamic>> fetchLatestArticles(int page) async {
try {
var response = await http.get(
'$WORDPRESS_URL/wp-json/wp/v2/posts/?page=$page&per_page=10&_fields=id,date,title,content,custom,link');
if (this.mounted) {
if (response.statusCode == 200) {
setState(() {
latestArticles.addAll(json
.decode(response.body)
.map((m) => Article.fromJson(m))
.toList());
if (latestArticles.length % 10 != 0) {
_infiniteStop = true;
} else {
_infiniteStop = false;
}
});
return latestArticles;
}
setState(() {
_infiniteStop = true;
});
}
} on SocketException {
throw 'No Internet connection';
}
return latestArticles;
}
here is a sample of response from the api call
[
{
"id": "",
"date": "",
"link": " ",
"title": {
"rendered": " "
},
"content": {
"rendered": " ",
"protected": false
}
},
{
"id": "",
"date": " ",
"link": " ",
"title": {
"rendered": " "
},
"content": {
"rendered": " ",
"protected": false
}
}
]
You can copy paste run full code below
You can use latestArticles.addAll(articleFromJson(response.body));
code snippet
List<Article> articleFromJson(String str) => List<Article>.from(json.decode(str).map((x) => Article.fromJson(x)));
...
if (this.mounted) {
if (response.statusCode == 200) {
setState(() {
latestArticles.addAll(articleFromJson(response.body));
working demo
full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
List<Article> articleFromJson(String str) =>
List<Article>.from(json.decode(str).map((x) => Article.fromJson(x)));
String articleToJson(List<Article> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Article {
Article({
this.id,
this.date,
this.link,
this.title,
this.content,
});
String id;
String date;
String link;
Title title;
Content content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
id: json["id"],
date: json["date"],
link: json["link"],
title: Title.fromJson(json["title"]),
content: Content.fromJson(json["content"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"date": date,
"link": link,
"title": title.toJson(),
"content": content.toJson(),
};
}
class Content {
Content({
this.rendered,
this.protected,
});
String rendered;
bool protected;
factory Content.fromJson(Map<String, dynamic> json) => Content(
rendered: json["rendered"],
protected: json["protected"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
"protected": protected,
};
}
class Title {
Title({
this.rendered,
});
String rendered;
factory Title.fromJson(Map<String, dynamic> json) => Title(
rendered: json["rendered"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<Article> latestArticles = [];
bool _infiniteStop;
Function _future;
Future<List<Article>> fetchLatestArticles(int page) async {
try {
/*var response = await http.get(
'$WORDPRESS_URL/wp-json/wp/v2/posts/?page=$page&per_page=10&_fields=id,date,title,content,custom,link');*/
String jsonString = '''
[
{
"id": "123",
"date": "",
"link": " ",
"title": {
"rendered": "abc"
},
"content": {
"rendered": " ",
"protected": false
}
},
{
"id": "456",
"date": " ",
"link": " ",
"title": {
"rendered": "def"
},
"content": {
"rendered": " ",
"protected": false
}
}
]
''';
http.Response response = http.Response(jsonString, 200);
if (this.mounted) {
if (response.statusCode == 200) {
setState(() {
latestArticles.addAll(articleFromJson(response.body));
if (latestArticles.length % 10 != 0) {
_infiniteStop = true;
} else {
_infiniteStop = false;
}
});
return latestArticles;
}
setState(() {
_infiniteStop = true;
});
}
} on SocketException {
throw 'No Internet connection';
}
return latestArticles;
}
#override
void initState() {
_future = fetchLatestArticles;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future(1),
builder: (context, AsyncSnapshot<List<Article>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].title.rendered),
Spacer(),
Text(
snapshot.data[index].id,
),
],
),
));
});
}
}
}));
}
}
i am new to flutter and was trying to deserialize a geojson from my api.
the retrieved geojson looks something like this:
[
{
"_id": {
"$oid": "5e95d60049ebb0e6b45a34e6"
},
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
14.810392700000136,
50.8584471640001
],
[
14.867856893000067,
50.8643899540001
]
]
]
},
"properties": {
"ADMIN": "Test",
"ISO_A3": "TST",
"ISO_A2": "TS"
}
}
]
i tried to use the JSON to Dart page(https://javiercbk.github.io/json_to_dart/) to retrieve a model that i can use in flutter.. but it says that the generated code is invalid cause of the 3 lists inside the coordinate element
the problem in the generated code is here:
Geometry.fromJson(Map<String, dynamic> json) {
type = json['type'];
if (json['coordinates'] != null) {
coordinates = new List<List>();
json['coordinates'].forEach((v) { coordinates.add(new List.fromJson(v)); });
}
}
anybody can help me out to solve the 3 lists in the list problem?
You can copy paste run full code below
You can see Geometry class definition in full code
code snippet
class Geometry {
String type;
List<List<List<double>>> coordinates;
...
factory Geometry.fromJson(Map<String, dynamic> json) => Geometry(
type: json["type"],
coordinates: List<List<List<double>>>.from(json["coordinates"].map(
(x) => List<List<double>>.from(
x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
);
print(payloadList[0].id.oid);
print(payloadList[0].geometry.coordinates[0][0][0]);
print(payloadList[0].geometry.coordinates[0][0][1]);
print(payloadList[0].geometry.coordinates[0][1][0]);
print(payloadList[0].geometry.coordinates[0][1][1]);
output
I/flutter (25078): 5e95d60049ebb0e6b45a34e6
I/flutter (25078): 14.810392700000136
I/flutter (25078): 50.8584471640001
I/flutter (25078): 14.867856893000067
I/flutter (25078): 50.8643899540001
full code
import 'package:flutter/material.dart';
import 'dart:convert';
List<Payload> payloadFromJson(String str) =>
List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));
String payloadToJson(List<Payload> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Payload {
Id id;
String type;
Geometry geometry;
Properties properties;
Payload({
this.id,
this.type,
this.geometry,
this.properties,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
id: Id.fromJson(json["_id"]),
type: json["type"],
geometry: Geometry.fromJson(json["geometry"]),
properties: Properties.fromJson(json["properties"]),
);
Map<String, dynamic> toJson() => {
"_id": id.toJson(),
"type": type,
"geometry": geometry.toJson(),
"properties": properties.toJson(),
};
}
class Geometry {
String type;
List<List<List<double>>> coordinates;
Geometry({
this.type,
this.coordinates,
});
factory Geometry.fromJson(Map<String, dynamic> json) => Geometry(
type: json["type"],
coordinates: List<List<List<double>>>.from(json["coordinates"].map(
(x) => List<List<double>>.from(
x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
);
Map<String, dynamic> toJson() => {
"type": type,
"coordinates": List<dynamic>.from(coordinates.map((x) =>
List<dynamic>.from(
x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
};
}
class Id {
String oid;
Id({
this.oid,
});
factory Id.fromJson(Map<String, dynamic> json) => Id(
oid: json["\u0024oid"],
);
Map<String, dynamic> toJson() => {
"\u0024oid": oid,
};
}
class Properties {
String admin;
String isoA3;
String isoA2;
Properties({
this.admin,
this.isoA3,
this.isoA2,
});
factory Properties.fromJson(Map<String, dynamic> json) => Properties(
admin: json["ADMIN"],
isoA3: json["ISO_A3"],
isoA2: json["ISO_A2"],
);
Map<String, dynamic> toJson() => {
"ADMIN": admin,
"ISO_A3": isoA3,
"ISO_A2": isoA2,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
String jsonString = '''
[
{
"_id": {
"\$oid": "5e95d60049ebb0e6b45a34e6"
},
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
14.810392700000136,
50.8584471640001
],
[
14.867856893000067,
50.8643899540001
]
]
]
},
"properties": {
"ADMIN": "Test",
"ISO_A3": "TST",
"ISO_A2": "TS"
}
}
]
''';
List<Payload> payloadList = payloadFromJson(jsonString);
print(payloadList[0].id.oid);
print(payloadList[0].geometry.coordinates[0][0][0]);
print(payloadList[0].geometry.coordinates[0][0][1]);
print(payloadList[0].geometry.coordinates[0][1][0]);
print(payloadList[0].geometry.coordinates[0][1][1]);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}