Error when pasting json code converted into dart in flutter project - json

I am following a tutorial where I'm supposed to convert a json code(provided by the instructor) to dart code using online converter, but when I paste the code in my project it gives number of errors errors which I am not able to fix. I'm still a beginner please help.
class ExerciseHub {
List<Exercises> exercises;
ExerciseHub({this.exercises});
ExerciseHub.fromJson(Map<String, dynamic> json) {
if (json['exercises'] != null) {
exercises = new List<Exercises>();
json['exercises'].forEach((v) {
exercises.add(new Exercises.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.exercises != null) {
data['exercises'] = this.exercises.map((v) => v.toJson()).toList();
}
return data;
}
}
class Exercises {
String id;
String title;
String thumbnail;
String gif;
String seconds;
Exercises({this.id, this.title, this.thumbnail, this.gif, this.seconds});
Exercises.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
thumbnail = json['thumbnail'];
gif = json['gif'];
seconds = json['seconds'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['thumbnail'] = this.thumbnail;
data['gif'] = this.gif;
data['seconds'] = this.seconds;
return data;
}
}
Following is the screenshot of errors I got
[1]: https://i.stack.imgur.com/EuHUd.png

I assume you're using a recent version of Flutter (2.2 or higher) which comes with Dart null-safety by default. Unfortunately, the code sample you have isn't written in null-safe Dart. Maybe the online converter doesn't support it?
The Dart version required for your project is defined in pubspec.yaml. Starting from Dart 2.12, null-safety is applied.
environment:
sdk: '>=2.12.0 <3.0.0'
Check if the online converter supports Dart 2.12 or higher or else you can add the following comment to the top of your file to change the Dart version of that specific file:
// #dart=2.9
class ExerciseHub {
...

Related

Flutter store List of custom Classes in Shared Preferences

I have List of custom objects which also have fields with non-primitive datatypes. I would like to store a list of these objects in SharedPreferences. This is my List and also the simple Data:
#JsonSerializable()
class MedicamentsBase {
final List<Medicament> data;
const MedicamentsBase({
required this.data,
});
factory MedicamentsBase.fromJson(Map<String, dynamic> json) =>
_$MedicamentsBaseFromJson(json);
Map<String, dynamic> toJson() => _$MedicamentsBaseToJson(this);
}
#JsonSerializable()
class Medicament {
#JsonKey(name: '_id')
String id;
String name;
int dosageAmount;
String dosageType;
DateTime startDate;
DateTime endDate;
List<DateTime> timesOfDay;
String intakeContext;
bool notify;
int notificationId;
Medicament({
required this.name,
required this.dosageAmount,
required this.dosageType,
required this.startDate,
required this.endDate,
required this.timesOfDay,
required this.intakeContext,
required this.notify,
required this.notificationId,
required this.id,
});
factory Medicament.fromJson(Map<String, dynamic> json) =>
_$MedicamentFromJson(json);
Map<String, dynamic> toJson() => _$MedicamentToJson(this);
}
I already serialized them. But if I try to store the MedicamentsBase like this:
static Future<void> setMedicaments(List<Medicament> medicaments) async {
final SharedPreferences _sharedPreferences =
await SharedPreferences.getInstance();
await _sharedPreferences.setStringList(
'key',
medicaments.map((medicament) => json.encode(medicament)).toList(),
);
}
Things are not working as expected if trying to get the List back like this:
static Future<List<Medicament>> getMedicaments() async {
final SharedPreferences _sharedPreferences =
await SharedPreferences.getInstance();
return MedicamentsBase.fromJson(
_sharedPreferences.getStringList('key') as Map<String, dynamic>,
).data;
}
I think it is because Medicament also has Strings and DateTimes in it. What is the correct way to store and get this kind of data in Shared Preferences?
Shared preferences might not be the way to go if you are intending on saving more complex data types, I think your options are:
Checking out on how to use the hive package
Trying to save primitive type which you can later use to reconstruct your complex data types with using shared preferences
Create a ToJson / FromJson functions in your complex data types, and use the file.dart function which are available as part of flutter to save this data as a json file, take alook at those functions which should be useful to do so:
write the file:
Directory applicationDocumentDirectory =
await getApplicationDocumentsDirectory();
File file = Directory applicationDocumentDirectory =
await getApplicationDocumentsDirectory();
Map<String, dynamic> fileJson = yourDataType.toJson();
String dataAsJsonString = jsonEncode(fileJson);
songDataFile.writeAsStringSync(dataAsJsonString);
String fileData = file.readAsStringSync();
return jsonDecode(fileData);
read the file:
Directory applicationDocumentDirectory =
await getApplicationDocumentsDirectory();
File file = Directory applicationDocumentDirectory =
await getApplicationDocumentsDirectory();
String fileData = file.readAsStringSync();
return jsonDecode(fileData);
Hopefully those ideas help :)

Flutter Persistence: how to jsonDecode a List<dynamic> to List<ClassType>?

I have a Todo-List app with Task class.
I want to serialize a Task List with jsonEncode and persist them onto a file in Docs dir.
after that, I want to be able to re-serialize the same list and convert them into my native List datatype (from List<String, dynamic> that I get from jsonDecode). Whats the best way to do it?
Currently, I tried:
void reSerializeTaskList() async {
final directory = await getApplicationDocumentsDirectory();
File f = File('${directory.path}/new.txt');
String fileContent = await f.readAsString();
List<dynamic> jsonList = jsonDecode(fileContent).cast<Task>(); // does not work
print("JSONSTRING: ${jsonList.runtimeType}");
print("$jsonList");
}
I/flutter (29177): JSONSTRING: CastList<dynamic, Task>
E/flutter (29177): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Task' in type cast
my workaround is to iterate through all array elements and build a Task type out of the values with "fromJson" method inside my Task class:
void reSerializeTaskList() async {
final directory = await getApplicationDocumentsDirectory();
File f = File('${directory.path}/new.txt');
String fileContent = await f.readAsString();
List<dynamic> jsonList = jsonDecode(fileContent);
List<Task> taskList = [];
for (var t in jsonList) {
print("T: $t and ${t.runtimeType}");
Task task = new Task();
taskList.add(task.fromJson(t));
}
print("JSONSTRING: ${jsonList.runtimeType}");
print("$jsonList");
print("$taskList");
print("$taskList.runtimeType");
}
my Task class:
import 'dart:io';
class Task {
String name;
bool isDone;
Task({this.name, this.isDone = false});
void toggleDone() {
isDone = !isDone;
}
#override
String toString() {
// TODO: implement toString
return "${this.name} is done: $isDone";
}
Map<String, dynamic> toJson() {
return {
"name": this.name,
"isDone": this.isDone,
};
}
Task fromJson(Map<String, dynamic> json) {
this.name = json['name'];
this.isDone = json['isDone'];
return this;
}
}
But is there maybe another (better) approach? This looks quite patchy to me...
Just to give you a little example, this is how I do it
final jsonResponse = json.decode(jsonString);
final List<Customer> customers = jsonResponse.map<Customer>((jR) => Customer.fromJson(jR)).toList();
and fromJson in Customer class looks like this
factory Customer.fromJson(Map<String, dynamic> json) => Customer(
id: json["id"] == null ? null : json["id"],
changeDate: json["changeDate"] == null ? null : DateTime.parse(json["changeDate"]),
name: json["name"] == null ? null : json["name"],
);

How to retrieve json data elements in to list view.builder in flutter?

I am using below code to fetch elements of json data from the mysql server in flutter application. In which I am successful to fetch data.
class CompanyDetail {
String error;
List<Content> content;
CompanyDetail({this.error, this.content});
CompanyDetail.fromJson(Map<String, dynamic> json) {
error = json['error'];
if (json['content'] != null) {
content = new List<Content>();
json['content'].forEach((v) {
content.add(new Content.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
if (this.content != null) {
data['content'] = this.content.map((v) => v.toJson()).toList();
}
return data;
}
}
class Content {
String id;
String name;
Content({this.id, this.name});
Content.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Then bind the Json data:
var companyDetail = CompanyDetail.fromJson(json.decode(response.body));
Now I need to access the json elements through this in list view builder in flutter but I am not getting any idea how to access those elements
companyDetail.content
This is the JSON data to be fetched and build the list
JSON DATA
{"error":"false",
"content":[
{
"id":"22","name":"Johnny",},
{"id":"23","name":"Maria",},
]
}
please guide me how can I get the elemental data of the JSON and get it into Listview.builder's ListTile?
Hope this helps this code will help to access the data inside the contents from your JSON structure and map it to variables.
var jsonDecode = json.decode(jsonFile);
//Decode your json file
//then map the content details to a variable.
var content = jsonDecode['content'];
// Since data inside your json eg above is a list.
// access the first element of the list and map to a var.
var firstdata= content[0];
// then map the id and name to a variable.
String id=firstdata['id'];
String name = firstdata['name'];
use this inside the list tile inside a text widget
Access companyDetail["content"]

json_serializable fails to deserialize

I am trying to add json support to my flutter project but has some hard time getting it right.
I love flutter but when it comes to json I wish for gson.
I have created a small project that exemplifies my problem.
Please se https://bitbucket.org/oakstair/json_lab
I get the error
type 'Match' is not a subtype of type 'Map' in type cast when trying to run the simple to/from json test.
There is obviously something that I miss here!
Thanks in advance from a stormy Stockholm!
import 'package:json_annotation/json_annotation.dart';
part 'json_lab.g.dart';
#JsonSerializable()
class Match {
int home;
int away;
double homePoints;
double awayPoints;
Match(this.home, this.away, {this.homePoints, this.awayPoints});
factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json);
Map<String, dynamic> toJson() => _$MatchToJson(this);
}
#JsonSerializable()
class Tournament {
List<String> participants; // Teams or Players.
List<List<Match>> table = new List<List<Match>>();
Tournament(this.participants, {this.table});
factory Tournament.fromJson(Map<String, dynamic> json) => _$TournamentFromJson(json);
Map<String, dynamic> toJson() => _$TournamentToJson(this);
}
Because I cannot see your json data I've made assumptions on the information you've provided on naming the objects. You'll need to change the following to match the json names (case sensitive).
Try the following to create your Match object
#JsonSerializable(nullable: true) //allow null values
class Match extends Object with _$MatchSerializerMaxin {
int home;
int away;
double homePoints;
double awayPoints;
Match({this.home, this.away, this.homePoints, this.awayPoints});
factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json);
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["Home"] = home;
map["Away"] = away;
map["HomePoints"] = homePoints;
map["AwayPoints"] = awayPoints;
return map;
}
Match.fromMap(Map map){
try{
home = map["Home"] as int;
away = map["Away"] as int;
homePoints = map["HomePoints"] as double;
awayPoints = map["AwayPoints"] as double;
}catch(e){
print("Error Match.fromMap: $e");
}
}
}
Match _$MatchFromJson(Map<String, dynamic> json){
Match match = new Match(
home: json['Home'] as int,
away: json['Away'] as int,
homePoints: json['HomePoints'] as double,
awayPoints: json['AwayPoints'] as double,
);
return match;
}
abstract class _$MatchSerializerMaxin {
int get home;
int get away;
double get homePoints;
double get awayPoints;
Match<String, dynamic> toJson() => <String, dynamic>{
'Home' : home,
'Away' : away,
'HomePoints' : homePoints,
'AwayPoints' : awayPoints
};
}
I just committed a solution to this problem to the repo.
I had to add explicitToJson.
#JsonSerializable(explicitToJson: true)

JSON serialization and deserialization to objects in Flutter

Since Flutter took out dart: mirrors off of its SDK, it's no longer possible to use libraries like dartson for JSON to object serialization/deserialization. However I've read that built_value is another way of achieving a similar purpose. I couldn't find any good examples on how to implement it as it contains a significant amount of boilerplate code. Can someone give me an example? For instance, this is the JSON I'm trying to serialize to objects:
{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
I was hoping for more details from the answers provided. Even though they were good suggestions, they were too general for me to understand. So after doing my own research, I'll share my implementation to the above JSON example I provided in hope that it would save someone's else's time. So here are the steps I followed:
In my Flutter project, first I imported the following libraries:
dependencies:
built_value: ^1.0.1
built_collection: ^1.0.0
dev_dependencies:
build_runner: ^0.3.0
built_value_generator:^1.0.1
I created a folder called tool. In it, I put 2 files: build.dart and watch.dart. There implementations of those files are show below
build.dart
// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build_runner/build_runner.dart';
import 'package:built_value_generator/built_value_generator.dart';
import 'package:source_gen/source_gen.dart';
/// Example of how to use source_gen with [BuiltValueGenerator].
///
/// Import the generators you want and pass them to [build] as shown,
/// specifying which files in which packages you want to run against.
Future main(List<String> args) async {
await build(
new PhaseGroup.singleAction(
new GeneratorBuilder([new BuiltValueGenerator()]),
new InputSet('built_value_example', const [
'lib/model/*.dart',
'lib/*.dart',
])),
deleteFilesByDefault: true);
}
watch.dart
// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import 'dart:async';
import 'package:build_runner/build_runner.dart';
import 'package:built_value_generator/built_value_generator.dart';
import 'package:source_gen/source_gen.dart';
/// Example of how to use source_gen with [BuiltValueGenerator].
///
/// This script runs a watcher that continuously rebuilds generated source.
///
/// Import the generators you want and pass them to [watch] as shown,
/// specifying which files in which packages you want to run against.
Future main(List<String> args) async {
watch(
new PhaseGroup.singleAction(
new GeneratorBuilder([new BuiltValueGenerator()]),
new InputSet('built_value_example', const [
'lib/model/*.dart',
'lib/*.dart'])),
deleteFilesByDefault: true);
}
I created a serializers.dart file that would serialize my json string to my custom dart object, and my model object person.dart
serializers.dart
library serializers;
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
import 'model/person.dart';
part 'serializers.g.dart';
Serializers serializers = (
_$serializers.toBuilder()..addPlugin(new StandardJsonPlugin())
).build();
person.dart
library person;
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'person.g.dart';
abstract class Person implements Built<Person, PersonBuilder> {
String get name;
int get age;
BuiltList<Car> get cars;
Person._();
factory Person([updates(PersonBuilder b)]) = _$Person;
static Serializer<Person> get serializer => _$personSerializer;
}
abstract class Car implements Built<Car, CarBuilder> {
String get name;
BuiltList<String> get models;
Car._();
factory Car([updates(CarBuilder b)]) = _$Car;
static Serializer<Car> get serializer => _$carSerializer;
}
After creating the 4 files above, it will show some compiler errors. Don't mind them yet. This is because the build.dart file hasn't been run yet. So in this step, run build.dart. If you're using Webstorm, simply right click on build.dart and hit "Run build.dart". This will create 2 files: "person.g.dart" and "serializers.g.dart". If you notice carefully, in our build.dart file, we put 'lib/model/.dart' and 'lib/.dart'. The build knows where to look for those files by going through the paths specified and looks for files which have part "something" included. So it's important to keep that line in those files before running the build.dart file
Finally, now I can use the serializer in my main.dart file to serialize the json string to my custom dart object class Person. In my main.dart, I added the following code in initState()
main.dart
Person _person;
#override
void initState() {
super.initState();
String json = "{"
"\"name\":\"John\",\"age\":30,\"cars\": "
"["
"{ \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },"
"{ \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },"
"{ \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }"
"]}";
setState(() {
_person = serializers.deserializeWith(
Person.serializer, JSON.decode(json));
});
}
My sample project is also available on Github Built value sample project
json_serialization
This package by the Dart Team generates everything needed for the fromJson constructor and toJson method in a seprate file.
Dependencies
Add the following dependencies:
dependencies:
json_annotation: ^2.0.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^2.0.0
Model class
Adapt your model class to have the following parts:
import 'package:json_annotation/json_annotation.dart';
// will be generated later
part 'person.g.dart';
#JsonSerializable()
class Person {
Person(this.name, this.age);
final String name;
final int age;
factory Person.fromJson(Map<String, dynamic> json) =>
_$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
Generate code
Generate the person.g.dart file from the terminal:
flutter packages pub run build_runner build
Use it
Then use it like this:
JSON → object
String rawJson = '{"name":"Mary","age":30}';
Map<String, dynamic> map = jsonDecode(rawJson);
Person person = Person.fromJson(map);
Object → JSON
Person person = Person('Mary', 30);
Map<String, dynamic> map = person.toJson();
String rawJson = jsonEncode(map);
Notes
In a Dart project use pub run build_runner build.
See this answer for more ways to serialize JSON.
From the Dart web site:
The dart:convert library provides a JsonCodec class, which you can use to convert simple types (map, list, int, num, string) automatically from a and to a JSON string. The two key static methods are JSON.encode(object) and JSON.decode(string).
Decoding example:
import 'dart:convert';
...
Map<String, dynamic> parsedMap = JSON.decode(json);
print(parsedMap['name']); // John
print(parsedMap['age']); // 30
Encoding example:
Map<String, dynamic> mapData = <String, dynamic>{ 'hello': 'world!' };
String jsonData = JSON.encode(mapData); // convert map to String
If you want to have your JSON inflate into custom Dart classes instead of a tree of primitive objects, Hadrien's answer should point you in the right direction, but I just wanted to leave this here in case anyone else is trying to get basic JSON serialization/deserialization working.
You can use Jaguar Serializer, it is easy to start and work perfectly for Flutter, or Server and Web dev.
https://github.com/Jaguar-dart/jaguar_serializer
You should prepare a configuration file for Built_value that will parse you dart source and generate the .g.dart. Once there are ready json serialisation is automatic. You can generate those files once or using a watch command.
Those file will be added at the same level than the source and the dart command
part of data;
to be seen as the same Class.
Here's the config I'm using with my Flutter project :
import 'dart:async';
import 'package:build_runner/build_runner.dart';
import 'package:built_value_generator/built_value_generator.dart';
import 'package:source_gen/source_gen.dart';
Future main(List<String> args) async {
await build(
new PhaseGroup.singleAction(
new GeneratorBuilder([
new BuiltValueGenerator(),
]),
new InputSet('flutter_project', const ['lib/data/*.dart'])),
deleteFilesByDefault: true);
}
You may find useful to read all the posts by David Morgan to understand the benefits. It need some time to turn your mind around but it's a very good pattern.
https://medium.com/dartlang/darts-built-value-for-immutable-object-models-83e2497922d4
https://medium.com/dartlang/darts-built-value-for-serialization-f5db9d0f4159
The trick is to understand how sourcegen parse and then enrich your classes by adding a lot of behaviors like Builders and Serializers.
1) first put json code to any convert website ex:
[JSON to Darthttps://javiercbk.github.io ›][1]
it will give like this output
class Autogenerated {
int? code;
List<Result>? result;
String? status;
Autogenerated({this.code, this.result, this.status});
Autogenerated.fromJson(Map<String, dynamic> json) {
code = json['code'];
if (json['result'] != null) {
result = <Result>[];
json['result'].forEach((v) {
result!.add(new Result.fromJson(v));
});
}
status = json['status'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
if (this.result != null) {
data['result'] = this.result!.map((v) => v.toJson()).toList();
}
data['status'] = this.status;
return data;
}
}
class Result {
int? id;
int? projectId;
String? projectName;
int? userId;
String? userName;
Result(
{this.id, this.projectId, this.projectName, this.userId, this.userName});
Result.fromJson(Map<String, dynamic> json) {
id = json['id'];
projectId = json['project_id'];
projectName = json['project_name'];
userId = json['user_id'];
userName = json['user_name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['project_id'] = this.projectId;
data['project_name'] = this.projectName;
data['user_id'] = this.userId;
data['user_name'] = this.userName;
return data;
}
}
--------------------------------------------------------------------------------------
and change that code like this format for easy use
***get_client.dart***
import 'package:json_annotation/json_annotation.dart';
part 'get_client.g.dart';
#JsonSerializable(
explicitToJson: true,
)
class ClientModel {
#JsonKey(name: "address1")
String? address1;
#JsonKey(name: "city")
int? city;
#JsonKey(name: "city_name")
String? cityName;
#JsonKey(name: "country")
int? country;
#JsonKey(name: "country_name")
String? countryName;
#JsonKey(name: "email")
String? email;
#JsonKey(name: "first_name")
String? firstName;
#JsonKey(name: "gender")
String? gender;
#JsonKey(name: "id")
int? id;
#JsonKey(name: "last_name")
String? lastName;
#JsonKey(name: "mobile_no")
String? mobileNo;
#JsonKey(name: "password")
String? password;
#JsonKey(name: "pincode")
String? pincode;
#JsonKey(name: "role")
int? role;
#JsonKey(name: "role_name")
String? roleName;
#JsonKey(name: "state")
int? state;
#JsonKey(name: "state_name")
String? stateName;
ClientModel(
{this.address1,
this.city,
this.cityName,
this.country,
this.countryName,
this.email,
this.firstName,
this.gender,
this.id,
this.lastName,
this.mobileNo,
this.password,
this.pincode,
this.role,
this.roleName,
this.state,
this.stateName});
factory ClientModel.fromJson(Map<String, dynamic> map) =>
_$ClientModelFromJson(map);
Map<String, dynamic> toJson() => _$ClientModelToJson(this);
}
-------------------------------------------------------------------
[1]: https://%20JSON%20to%20Darthttps://javiercbk.github.io%20%E2%80%BA
after run build runner cmd in terminal
***flutter pub run build_runner build***
then it will create the following output file
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'get_client.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ClientModel _$ClientModelFromJson(Map<String, dynamic> json) => ClientModel(
address1: json['address1'] as String?,
city: json['city'] as int?,
cityName: json['city_name'] as String?,
country: json['country'] as int?,
countryName: json['country_name'] as String?,
email: json['email'] as String?,
firstName: json['first_name'] as String?,
gender: json['gender'] as String?,
id: json['id'] as int?,
lastName: json['last_name'] as String?,
mobileNo: json['mobile_no'] as String?,
password: json['password'] as String?,
pincode: json['pincode'] as String?,
role: json['role'] as int?,
roleName: json['role_name'] as String?,
state: json['state'] as int?,
stateName: json['state_name'] as String?,
);
Map<String, dynamic> _$ClientModelToJson(ClientModel instance) =>
<String, dynamic>{
'address1': instance.address1,
'city': instance.city,
'city_name': instance.cityName,
'country': instance.country,
'country_name': instance.countryName,
'email': instance.email,
'first_name': instance.firstName,
'gender': instance.gender,
'id': instance.id,
'last_name': instance.lastName,
'mobile_no': instance.mobileNo,
'password': instance.password,
'pincode': instance.pincode,
'role': instance.role,
'role_name': instance.roleName,
'state': instance.state,
'state_name': instance.stateName,
};
after we can use like this in repository file
static Future<dynamic> getAllClients(int id) async {
String url = "${HttpUrls.clientList}/${0}";
Response response = await dio.get(url);
if (response.statusCode == 200) {
List<ClientModel> clientLists = (response.data['result'] as List)
.map((eachItem) => ClientModel.fromJson(eachItem))
.toList();
print(clientLists.toString());
if (clientLists.isNotEmpty) {
return clientLists;
}
} else {
BaseResponse baseResponse =
BaseResponse.fromJson(response.data as Map<String, dynamic>);
return baseResponse;
}
}