I want to showing this value to listview on flutter
[{"No":0,"interest":"0.00","balance":"13,000,000.00","principal":"0.00","Installment":"0.00","Status":true},{"No":1,"interest":"130,000.00","balance":"0.00","principal":"13,000,000.00","Installment":"13,130,000.00","Status":true}]
but i get the result like
I/flutter (12074): Error FormatException: Unexpected character (at character 1)
I/flutter (12074): <br />
I/flutter (12074): ^
I/flutter (12074):
here is my List LoanModel
static Future<List<LoanModel>> getsimulation({String periodtime, String interestpermonth, String loanamountrequest, String idUser, String url}) async {
var url = "http://192.168.0.23/edufund-api/Api/loansimulation.php?periodtime=" + periodtime + "&interestpermonth=" + interestpermonth + "&loanamountrequest=" +loanamountrequest;
final response = await http.get(url,headers:{"Content-Type":
"application/json"});
var res = LoanModel.fromJson(jsonDecode(response.body)[0]);
print(response.body);
}
here is the function to load JSON when already input value periodtime, interestpermonth and loanamountrequest
_load() async {
List<LoanModel> loanmodel =
(await RestApi.getsimulation());
setState(() => _loanmodel = loanmodel);
}
Here is my Model
List<LoanModel> allLoan(String str) {
final jsonData = json.decode(str);
return new List<LoanModel>.from(jsonData.map((x) => LoanModel.fromJson(x)));
}
class LoanModel {
bool Status;
String message;
String No;
String interest;
String balance;
String principal;
String Installment;
List<Data> data;
LoanModel({
this.Status,
this.message,
this.No,
this.interest,
this.balance,
this.principal,
this.Installment,
this.data,
});
factory LoanModel.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['data'] as List;
print(list.runtimeType);
List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();
return LoanModel(
Status: parsedJson['Status'],
message: parsedJson['message'],
No : parsedJson['No'],
interest: parsedJson['interest'],
balance: parsedJson['balance'],
principal: parsedJson['principal'],
Installment: parsedJson['Installment'],
data: dataList,
);
}
}
class Data {
final int No;
final String interest;
final String balance;
final String principal;
final String Installment;
Data({
this.No,
this.interest,
this.balance,
this.principal,
this.Installment
});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
return Data(
No: parsedJson['No'],
interest: parsedJson['interest'],
balance: parsedJson['balance'],
principal: parsedJson['principal'],
Installment: parsedJson['Installment']
);
}
and the result is keep loading like this
The output should be like this
How can i make output like picture number 2 and how to resolved this Unexpected character in flutter?
thank you
I am able to parse it with the JSON locally. Update the dataModel:
import 'dart:convert';
List<LoanModel> loanModelFromJson(String str) => List<LoanModel>.from(json.decode(str).map((x) => LoanModel.fromJson(x)));
String loanModelToJson(List<LoanModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class LoanModel {
LoanModel({
this.no,
this.interest,
this.balance,
this.principal,
this.installment,
this.status,
});
int no;
String interest;
String balance;
String principal;
String installment;
bool status;
factory LoanModel.fromJson(Map<String, dynamic> json) => LoanModel(
no: json["No"],
interest: json["interest"],
balance: json["balance"],
principal: json["principal"],
installment: json["Installment"],
status: json["Status"],
);
Map<String, dynamic> toJson() => {
"No": no,
"interest": interest,
"balance": balance,
"principal": principal,
"Installment": installment,
"Status": status,
};
}
Any try to parse it like this:
arr = loanModelFromJson(response.body);
RestAPI call
class APIManager {
final String baseURL = [BaseURL];
getData(apiUrl) async {
var fullUrl = baseURL + apiUrl;
return await http.get(Uri.parse(fullUrl), headers: _setHeader());
}
}
Future<void> getData() async {
var response = await APIManager().getData([Endpoint]);
arr = loanModelFromJson(response.body);
}
Related
im new in Dart/Flutter and im struggling with consuming API, here is my file thats inside my model folder:
List<Heroes> heroesFromJson(String str) =>
List<Heroes>.from(json.decode(str).map((x) => Heroes.fromJson(x)));
String heroesToJson(List<Heroes> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Heroes {
Heroes({
required this.id,
required this.name,
required this.localizedName,
required this.primaryAttr,
required this.attackType,
required this.roles,
});
int id;
String name;
String localizedName;
String primaryAttr;
String attackType;
List<String> roles;
factory Heroes.fromJson(Map<String, dynamic> json) => Heroes(
id: json["id"],
name: json["name"],
localizedName: json["localized_name"],
primaryAttr: json["primary_attr"],
attackType: json["attack_type"],
roles: List<String>.from(json["roles"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"localized_name": localizedName,
"primary_attr": primaryAttr,
"attack_type": attackType,
"roles": List<dynamic>.from(roles.map((x) => x)),
};
}
And here is where im getting the error, inside services folder:
class DotaServices {
Future<List<String>?> getHeroes() async {
var client = http.Client();
var url = Uri.parse('https://api.opendota.com/api/heroes');
var response = await client.get(url);
if (response.statusCode == 200) {
var json = response.body;
return heroesFromJson(json);
}
}
}
The error is occuring in that line:
return heroesFromJson(json);
And the message that appears is:
A value of type 'List<Heroes>' can't be returned from the method 'getHeroes' because it has a return type of 'Future<List<String>?>'.
how to solve it? Im struggling real hard on this :/
Your method returns a list of heroes... so... you need to return a list of heroes:
Future<List<String>?> getHeroes() async {
needs to be
Future<List<Heroes>?> getHeroes() async {
heroesFromJson returns a list of heroes so getHeroes has to return a list of heroes:
Future<List<Heroes>?> getHeroes()
Also, your method heroesFromJson returns a List<Heroes> not nullable, but your method getHeroes() return a List<Heroe>? which is nullable.
You either can make your return from heroesFromJson a nullable list List<T>? or your return from getHeroes() a non-nullable list List
Be careful making your List nullable or non-nullable List<Hero>?, not your Hero List<Hero?>
It seems to me that such code should work more reliably.
return Hero.fromJsonList(json as List);
This small example (including function main) was generated with a very small script.
import 'dart:convert';
import 'package:http/http.dart' as http;
void main(List<String> args) async {
final svc = DotaServices();
final heroes = await svc.getHeroes();
print('Heroes: ${heroes.length}');
}
class DotaServices {
Future<List<Hero>> getHeroes() async {
final client = http.Client();
final url = Uri.parse('https://api.opendota.com/api/heroes');
final response = await client.get(url);
if (response.statusCode == 200) {
final source = response.body;
final json = jsonDecode(source);
return Hero.fromJsonList(json as List);
}
throw StateError('Http error: ${response.statusCode}');
}
}
class Hero {
Hero(
{required this.id,
required this.name,
required this.localizedName,
required this.primaryAttr,
required this.attackType,
required this.roles});
factory Hero.fromJson(Map json) {
return Hero(
id: json['id'] as int,
name: json['name'] as String,
localizedName: json['localized_name'] as String,
primaryAttr: json['primary_attr'] as String,
attackType: json['attack_type'] as String,
roles: json['roles'] == null
? []
: (json['roles'] as List).map((e) => e as String).toList(),
);
}
final int id;
final String name;
final String localizedName;
final String primaryAttr;
final String attackType;
final List<String> roles;
static List<Hero> fromJsonList(List json) {
return json.map((e) => Hero.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'localized_name': localizedName,
'primary_attr': primaryAttr,
'attack_type': attackType,
'roles': roles,
};
}
static List<Map<String, dynamic>> toJsonList(List<Hero> list) {
return list.map((e) => e.toJson()).toList();
}
}
Using this codegen script you can generate the models and serializers.
It also generates a working example.
import 'dart:io';
import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';
void main() {
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);
final values = {
'classes': classesCode,
};
var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}
const _classes = '''
Hero:
fields:
id: int
name: String
localizedName: {type: String, alias: localized_name}
primaryAttr: {type: String, alias: primary_attr}
attackType: {type: String, alias: attack_type}
roles: List<String>
''';
const _template = r'''
import 'dart:convert';
import 'package:http/http.dart' as http;
void main(List<String> args) async {
final svc = DotaServices();
final heroes = await svc.getHeroes();
print('Heroes: ${heroes.length}');
}
class DotaServices {
Future<List<Hero>> getHeroes() async {
final client = http.Client();
final url = Uri.parse('https://api.opendota.com/api/heroes');
final response = await client.get(url);
if (response.statusCode == 200) {
final source = response.body;
final json = jsonDecode(source);
return Hero.fromJsonList(json as List);
}
throw StateError('Http error: ${response.statusCode}');
}
}
{{classes}}
''';
I'm new to programming and currently learning JSON. I got this error when using Cubit to access the JSON:
RestaurantFailed(type 'Null' is not a subtype of type 'List<RestaurantModel>')
JSON Sample: https://restaurant-api.dicoding.dev/list
I'm trying to access the API and insert it to RestaurantModel.
this is my code:
restaurant_service.dart
class RestaurantService {
Future<List<RestaurantModel>> fetchAllData() async {
try {
Uri url = Uri.http('restaurant-api.dicoding.dev', '/list');
http.Response response = await http.get(url);
Map<String, dynamic> result = jsonDecode(response.body);
List<RestaurantModel> restaurants = result['restaurants'].forEach((json) {
return RestaurantModel.fromJson(json: json);
});
return restaurants;
} catch (e) {
rethrow;
}
}
}
restaurant_cubit.dart
class RestaurantCubit extends Cubit<RestaurantState> {
RestaurantCubit() : super(RestaurantInitial());
void fetchData() async {
try {
emit(RestaurantLoading());
List<RestaurantModel> restaurants =
await RestaurantService().fetchAllData();
emit(RestaurantSuccess(restaurants));
} catch (e) {
emit(RestaurantFailed(e.toString()));
}
}
}
restaurant_model.dart
class RestaurantModel {
final String id;
final String name;
final String description;
final String pictureId;
final String city;
final double rating;
String? address;
List<String>? categories;
List<String>? menus;
List<CustomerReviewModel>? customerReviews;
RestaurantModel({
required this.id,
required this.name,
required this.description,
required this.pictureId,
required this.city,
this.rating = 0.0,
this.address = '',
this.categories,
this.menus,
this.customerReviews,
});
factory RestaurantModel.fromJson({required Map<String, dynamic> json}) =>
RestaurantModel(
id: json['id'],
name: json['name'],
description: json['description'],
pictureId: json['pictureId'],
city: json['city'],
rating: json['rating'].toDouble(),
address: json['address'] ?? '',
categories: json['categories'] ?? [],
menus: json['menus'] ?? [],
customerReviews: json['customerReviews'] ?? [],
);
}
any feedback or input would be very appreciated! Cheers
The forEach should be replaced by map(...).toList() like the following code snippet:
List<RestaurantModel> restaurants = result['restaurants'].map((json) {
return RestaurantModel.fromJson(json: json);
}).toList();
This is because forEach returns void and it cannot be assigned to anything. On the other hand, map returns a Iterable<RestaurantModel> and it's just a matter of converting it to list with the toList() method.
I'm carrying out a basic fetch API request in the code below. The response I'm receiving gives the values for most of the properties except for two which come as null. This has me thinking if it is my code that's causing this issue to occur or something on the backend side which results into this anomaly. As shown below, the fiels that come as null in my VS Code terminal are product_description and restaurant_id. Although these come as null when displayed on the terminal, on Postman it is a different story as the response comes in full. The code and the responses are as follows:
Response on Postman:
{
"status": "success",
"data": [
{
"product_id": 8,
"restaurant_name": "Mocambo",
"restaurant_id": "6", //This is the field in question
"product_name": "Kaju Paneer",
"product_description": "Tasty yummy paneer gravy dish", //And So is this
"product_image": "/public/assets/product/lgml5L03-19-41.jpg",
"product_selling_price": "320"
}
]
}
Response received on Terminal after API Call:
{"status":"success","data":[{"product_id":8,"restaurant_name":"Mocambo","restaurant_id":"6","product_name":"Kaju Paneer","product_description":"Tasty yummy paneer gravy dish","product_image":"\/public\/assets\/product\/lgml5L03-19-41.jpg","product_selling_price":"320"}
When I try printing all the properties this is what I get(You can see above that I still receive data for restaurant_id and product_description)
I/flutter (10235): Provider product_selling_price 320
I/flutter (10235): Provider product_image /public/assets/product/lgml5L03-19-41.jpg
I/flutter (10235): Provider product_name Kaju Paneer
I/flutter (10235): Provider product_id 8
I/flutter (10235): Provider restaurantName Mocambo
I/flutter (10235): Provider Restaurant ID null //Restaurant ID here comes as null
I/flutter (10235): Provider Restaurant Description null //Restaurant Description comes as null
The codes for the Model Class, the class from which the API is called and the widget where it is used are below:
Model Class
import 'package:meta/meta.dart';
import 'dart:convert';
PopularDishes popularDishesFromJson(String str) =>
PopularDishes.fromJson(json.decode(str));
String popularDishesToJson(PopularDishes data) =>
json.encode(data.toJson());
class PopularDishes {
PopularDishes ({
required this.status,
required this.data,
});
String status;
List<Datum> data;
factory PopularDishes .fromJson(Map<String, dynamic> json) =>
PopularRestaurants(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.productId,
required this.restaurantName,
required this.restaurantId,
required this.productName,
required this.productDescription,
required this.productImage,
required this.productSellingPrice,
});
int productId;
String restaurantName;
String restaurantId;
String productName;
String productDescription;
String productImage;
String productSellingPrice;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
productId: json["product_id"],
restaurantName: json["restaurant_name"],
restaurantId: json["restaurant_id"],
productName: json["product_name"],
productDescription: json["product_description"],
productImage: json["product_image"],
productSellingPrice: json["product_selling_price"],
);
Map<String, dynamic> toJson() => {
"product_id": productId,
"restaurant_name": restaurantName,
"restaurant_id": restaurantId,
"product_name": productName,
"product_description": productDescription,
"product_image": productImage,
"product_selling_price": productSellingPrice,
};
}
The class from where the API is called
class PopularDishesProvider with ChangeNotifier {
Map<String, dynamic> _popularDishes = {};
String baseUrl = 'https://achievexsolutions.in/current_work/eatiano/';
Map<String, dynamic> get popularDishes {
return {..._popularDishes};
}
Future<void> fetchData() async {
final url = Uri.parse(baseUrl + 'api/all_products');
final response = await http.get(url);
print(response.body);
PopularDishes popularDishes = popularDishesFromJson(response.body);
_popularDishes = popularDishes.toJson();
// print(_popularDishes);
}
}
The widget
class PopularDishes extends StatefulWidget {
PopularDishesState createState() => PopularDishesState();
}
class PopularDishesState extends State<PopularDishes> {
bool _isLoading = true;
#override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
Provider.of<PopularDishesProvider>(context).fetchData().then((_) {
setState(() {
_isLoading = false;
});
});
}
#override
Widget build(BuildContext context) {
var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;
var textScale = MediaQuery.of(context).textScaleFactor * 1.1;
var subTitleScale = MediaQuery.of(context).textScaleFactor * 1.4;
final provider = Provider.of<PopularDishesProvider>(context).popularDishes;
print(
'Provider product_selling_price ${provider['data'][0]['product_selling_price']}');
print('Provider product_image ${provider['data'][0]['product_image']}');
print('Provider product_name ${provider['data'][0]['product_name']}');
print('Provider product_id ${provider['data'][0]['product_id']}');
print('Provider restaurantName ${provider['data'][0]['restaurant_name']}');
print('Provider Restaurant ID ${provider['data'][0]['restaurant_id']}'); //Returns null here
print(
'Provider Restaurant Description ${provider['data'][0]['product_description']}'); //Returns null here
}
}
Is there anything I can do to fix this or is this a backend issue?
It may happen if some of your restaurant_id contains null value. If you are getting the response of data Try as follows:
provider['data'][0]['restaurant_id']==null?
print("isEmpty") :
print('Provider Restaurant ID ${provider['data'][0]['restaurant_id']}');
Note, I could not check your Model class because you did not provide PopularRestaurants. Also, I may be mistaken but I don't think you should make async-await function calls inside provider. First call fetchData in your StatefulWidget, then save the data in your provider. I also think you're using didChangeDependencies wrong and what you want is initstate.
This works for me:
Model Class generated from https://javiercbk.github.io/json_to_dart/
class PopularDishesModel {
String? status;
List<Data>? data;
PopularDishesModel({this.status, this.data});
PopularDishesModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = status;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int? productId;
String? restaurantName;
String? restaurantId;
String? productName;
String? productDescription;
String? productImage;
String? productSellingPrice;
Data(
{this.productId,
this.restaurantName,
this.restaurantId,
this.productName,
this.productDescription,
this.productImage,
this.productSellingPrice});
Data.fromJson(Map<String, dynamic> json) {
productId = json['product_id'];
restaurantName = json['restaurant_name'];
restaurantId = json['restaurant_id'];
productName = json['product_name'];
productDescription = json['product_description'];
productImage = json['product_image'];
productSellingPrice = json['product_selling_price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = productId;
data['restaurant_name'] = restaurantName;
data['restaurant_id'] = restaurantId;
data['product_name'] = productName;
data['product_description'] = productDescription;
data['product_image'] = productImage;
data['product_selling_price'] = productSellingPrice;
return data;
}
}
This is my stateful widget
class PopularDishes extends StatefulWidget {
PopularDishesState createState() => PopularDishesState();
}
class PopularDishesState extends State<PopularDishes> {
String baseUrl = 'https://achievexsolutions.in/current_work/eatiano/';
//Initialize PopularDishesModel
PopularDishesModel savedModel = PopularDishesModel();
//Make sure all json is downloaded
bool _isLoading = true;
//Remove this function from provider and put in your widget
Future<PopularDishesModel> fetchData() async {
final url = Uri.parse(baseUrl + 'api/all_products');
final response = await http.get(url);
//print(response.body);
PopularDishesModel popularDishes = PopularDishesModel.fromJson(json.decode(response.body));
return popularDishes;
}
//This is an async function f
void GetRestaurantData() async
{
PopularDishesModel result = await fetchData();
setState(() {
savedModel = result;
_isLoading = false;
});
}
#override
void initState() {
super.initState();
GetRestaurantData();
}
#override
Widget build(BuildContext context) {
var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;
var textScale = MediaQuery.of(context).textScaleFactor * 1.1;
var subTitleScale = MediaQuery.of(context).textScaleFactor * 1.4;
//Add code to save to provider
if(_isLoading == false) {
print(savedModel.data![0].productId);
print(savedModel.data![0].restaurantName);
print(savedModel.data![0].restaurantId);
print(savedModel.data![0].productName);
print(savedModel.data![0].productDescription);
print(savedModel.data![0].productImage);
print(savedModel.data![0].productSellingPrice);
/*Result
8
Mocambo
6
Kaju Paneer
Tasty yummy paneer gravy dish
/public/assets/product/lgml5L03-19-41.jpg
320*/
}
//Add logic to save to provider
return Container();
}
}
I am uploading images to a storageAPI using POST method with content-type of multipart/form-data. The api returns an object response that looks as below:
{
"id": "6d50c066-cf65-4748-8b9a-183c3526f49b",
"name": "hotel_6.jpg",
"fileKey": "lv/im/5d9feb8e-2ea8-439d-a550-1e937081e085-hotel_6.jpg",
"fileExtension": ".jpg",
"mimeType": "image/jpeg",
"catalogueUrl": {
"mainUrl": "https://xy.abc.com/lv/im/5d9feb8e-2ea8-439d-a550-1e937081e085-hotel_6.jpg",
"thumbnailUrls": []
},
"createdAt": "2021-11-25T06:40:40.0869466+00:00"
}
How can I extract the variable "mainUrl" from the response so that I can assign its value to the _pictureController? Here is what I have done:
uploadFile() async {
var accessToken = await sharedPref.read(key);
var postUrl = '$baseUrl/catalogue?thumbnail=${param.thumbnailTrueFalse}';
Map < String, String > headers = {
"Authorization": "Bearer $accessToken",
};
// multipart request object
var request = http.MultipartRequest("POST", Uri.parse(postUrl));
request.headers.addAll(headers);
// add selected file with request
request.files.add(http.MultipartFile("file", imageStream, imageSize,
filename: imageName));
// Send request
var response = await request.send();
// Read response
var result = await response.stream.bytesToString();
print('readResponse: $result');
if (response.statusCode == 200) {
var data = StorageResponse.fromJson(jsonDecode(result));
print('data: $data');
setState(() {
_pictureController.text = data.catalogueUrl!.mainUrl!;
});
return data;
} else {
throw Exception('Failed to upload photo.');
}
}
The "StorageResponse" Class is as follows:
#JsonSerializable()
class StorageResponse {
var id;
var name;
var fileKey;
var fileExtension;
var mimeType;
Catalogue ? catalogueUrl;
var createdAt;
StorageResponse({
this.id,
this.name,
this.fileKey,
this.fileExtension,
this.mimeType,
this.catalogueUrl,
this.createdAt,
});
factory StorageResponse.fromJson(Map < String, dynamic > json) =>
_$StorageResponseFromJson(json);
Map < String, dynamic > toJson() => _$StorageResponseToJson(this);
#override
toString() {
String output =
'{id:${this.id},name:${this.name},fileKey: ${this.fileKey},fileExtension:${this.fileExtension},mimeType: ${this.mimeType}mimeType},catalogueUrl: ${this.catalogueUrl},,createdAt: ${this.createdAt}}';
return output;
}
}
You can use the following structure to convert a Json file to a class, and vice versa.
The following structure works properly.
import 'dart:convert';
class StorageResponse {
final String id;
final String name;
final String fileKey;
final String fileExtension;
final String mimeType;
Catalogue catalogueUrl;
final DateTime createdAt;
StorageResponse(
this.id,
this.name,
this.fileKey,
this.fileExtension,
this.mimeType,
this.catalogueUrl,
this.createdAt,
);
factory StorageResponse.fromMap(Map<String, dynamic> json) {
return StorageResponse(
json['id'],
json['name'],
json['fileKey'],
json['fileExtension'],
json['mimeType'],
Catalogue.fromMap(json['Catalogue']),
DateTime.parse(json['createdAt']));
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'fileKey': fileKey,
'fileExtension': fileExtension,
'mimeType': mimeType,
'Catalogue': catalogueUrl.toJson(),
'createdAt': createdAt
};
#override
toString() {
String output =
'{id:${this.id},name:${this.name},fileKey: ${this.fileKey},fileExtension:${this.fileExtension},mimeType: ${this.mimeType}mimeType},catalogueUrl: ${this.catalogueUrl},,createdAt: ${this.createdAt}}';
return output;
}
}
class Catalogue {
final String mainUrl;
final List<String> thumbnailUrls;
Catalogue(this.mainUrl, this.thumbnailUrls);
factory Catalogue.fromMap(Map<String, dynamic> json) {
return Catalogue(json['mainUrl'], jsonDecode(json['thumbnailUrls']));
}
Map<String, dynamic> toJson() =>
{'mainUrl': mainUrl, 'thumbnailUrls': jsonEncode(thumbnailUrls)};
}
for use
if (response.statusCode == 200) {
var data = StorageResponse.fromMap(jsonDecode(result));
print('data: $data');
setState(() {
_pictureController.text = data.catalogueUrl!.mainUrl!;
});
return data;
} else {
throw Exception('Failed to upload photo.');
}
in flutter i should make this json structure for server side application:
{
"data": [
{
"staff_id": "barcode1",
"class_id": "session_id1",
"class_name": "session_name1",
"enter_date": "enter_date1",
"Exit_date": "exit_date1",
"username": "username1"
},
{
"staff_id": "barcode2",
"class_id": "session_id2",
"class_name": "session_name2",
"enter_date": "enter_date2",
"Exit_date": "exit_date2",
"username": "username2"
}
]
}
my code for implementing this structure:
class RestData{
final List<Data> data;
RestData({#required this.data});
Map<String, dynamic> toJson() => {
'data':data
};
}
class Data {
final String staff_id;
final String class_id;
final String class_name;
final String enter_date;
final String exit_date;
final String username;
Data({this.staff_id,this.class_id,this.class_name,this.enter_date,this.exit_date,this.username});
Data.fromJson(Map<String, dynamic> json)
: staff_id = json['staff_id'],
class_id = json['class_id'],
class_name = json['class_name'],
enter_date = json['enter_date'],
exit_date = json['exit_date'],
username = json['username'];
Map<String, dynamic> toJson() {
var map = new Map<String, dynamic>();
map["staff_id"] = staff_id;
map["class_id"] = class_id;
map["class_name"] = class_name;
map["enter_date"] = enter_date;
map["exit_date"] = exit_date;
map["username"] = username;
return map;
}
}
//--------------------------------------
List<Data> list = [];
for (int i = 0; i < barcodes.length; i++) {
list.add(Data(staff_id: 'aaa', class_id: '1111', class_name: '2222', enter_date: '3333', exit_date: '444444', username: '5555'));
}
result:
restData = {RestData}
data = {_GrowableList} size = 1
0 = {Data}
staff_id = "aaa"
class_id = "1111"
class_name = "2222"
enter_date = "3333"
exit_date = "444444"
username = "5555"
now! when i try to send this result to server i get this error:
List<Data> is not a subtype of type 'String' in type cast
my class to send data to server:
class SendInformation{
Future<bool> sendDataToServer(List<Data> list) async{
RestData restData = RestData(data: list);
final response = await http.post('http://sample.com',body:restData.toJson()).timeout(Duration(seconds: 60));
if(response.statusCode ==200){
return true;
}else{
return false;
}
}
}
I'm not sure but i think problem is in this line of code:
restData.toJson()
UPDATE TO JsonSerializable:
part 'rest_data.g.dart';
#JsonSerializable()
class RestData {
final List<Data> data;
RestData(this.data);
factory RestData.fromJson(Map<String, dynamic> json) => _$RestDataFromJson(json);
Map<String, dynamic> toJson() => _$RestDataToJson(this);
}
part 'data.g.dart';
#JsonSerializable()
class Data {
#JsonKey(name: 'staff_id')
String staffId;
#JsonKey(name: 'class_id')
String classId;
#JsonKey(name: 'class_name')
String className;
#JsonKey(name: 'enter_date')
String enterDate;
#JsonKey(name: 'exit_date')
String exitDate;
#JsonKey(name: 'username')
String username;
Data(this.staffId, this.classId, this.className, this.enterDate, this.exitDate, this.username);
factory Data.fromJson(Map<String, dynamic> json) => _$DataFromJson(json);
Map<String, dynamic> toJson() => _$DataToJson(this);
}
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class SendInformation{
Future<bool> sendDataToServer(List<Data> list) async{
RestData restData = RestData(data: list);
final response = await http.post('http://sample.com',body:json.encode(restData.toJson())).timeout(Duration(seconds: 60));
if(response.statusCode ==200){
return true;
}else{
return false;
}
}
}
Parse your json with json.encode(Your_JSON_String)