how to achieve object literals in dart - flutter

I have a class which has named constructor and I want to pass variable and eval the result as a class variable how can I achieve it like in javascript we have object literals and eval
I'm getting the data from server like [{path: 'fullName', msg: "Field is Required" }, {...}]
below is the example:
class Test{
String fullName;
Test({this.fullName});
}
Map ob = {fullName: "someAnotherName", another:another};
var t = Test(ob); //how to achieve this line
var varaible = "fullName";
t.[variable]; //how to achieve this line
`

It is common to write a named fromJson factory constructor which accpets a Map<String, dyanmic> as an argument which is the json data you will pass to it.
For the code you provided it would be like:
class Test{
String fullName;
Test({this.fullName});
factory Test.fromJson(Map<String, dynamic> json) {
return Test(
fullName: json['fullName'],
);
}
}
Map ob = {fullName: "someAnotherName", another:another};
var t = Test.fromJson(ob);
t.fullName;

Since your ob is a Map you can get fullname by writing
var name = ob['fullName'] or this way
var fullName = 'fullName';
var name = ob[fullName];
Both should contain someAnotherName

Related

Why Last value of a class object String assign to first one object in flutter

Click Here to see Dartpad Screenshot
void main(){
Student file1 = Student.empty;
Student file2 = Student.empty;
file1.name = 'ABC';
file2.name = 'DEF';
print(file1.name);
print(file2.name);
}
class Student{
String name;
Student({
required this.name,
});
static Student empty = Student(name: '');
}
Output Value
DEF
DEF
Expected Value
ABC
DEF
This happens, because you are using the same static instance of Student, since the static field is shared across all instances of Student.
So your variables file1 and file2 are referencing the same single instance of Student.
You may want to use a factory constructor instead:
https://dart.dev/guides/language/language-tour#factory-constructors
void main() {
Student file1 = Student.empty();
Student file2 = Student.empty();
file1.name = 'ABC';
file2.name = 'DEF';
print(file1.name);
print(file2.name);
}
class Student {
String name;
Student({
required this.name,
});
factory Student.empty() {
return Student(name: '');
}
}

How to extract key and value from JSON Object in flutter

I integrated API, I want to get both key and value from API response. I stored both key and value in two separate arrays and display inside the listview.so How to get key and value from api response.
[
{ "Name": "abc"
"Department": "Marketing",
"EmpCode": "ABC123",
"Salary":"20000",
"Pincode": 100023
}]
I got response using this code:
List list = json.decode(response.body);
So how to get Name,department,empcode and abc,marketing separate.
just use a forEach loop and it will extract keys and values for you which you can store according to your requirement and you don't have to worry about how many keys you have
response.forEach((key, value){
print('key is $key');
print('value is $value ');
}
Create a class that will hold your fields and add a fromJson method like so:
class ClassName{
ClassName(
{this.Name,
this.Department,
this.EmpCode,
this.Salary,
this.Pincode,
});
String Name;
String Department;
String EmpCode;
double Salary;
String Pincode;
ClassName.fromJson(Map<String, dynamic> json) {
Name= json['Name'];
Department= json['Department'];
EmpCode= json['EmpCode'];
Salary= json['Salary'];
Pincode= json['Pincode'];
}
}
And then you could do something like that with your json that you get from the API:
var x = json.decode(response.body.toString());
var className = ClassName.fromJson(x);

How to declare a List type property for a class correctly in Dart?

I am new to Flutter, and trying to declare a Folder class with one of the properties being a list of children Folders. I am not able to arrive to a correct declaration, the language gives me various errors. Someone can help me out with that?
class Folder {
final int id;
final String title;
final List<Folder> children;
Folder ({
this.id = 0,
this.title = '',
this.children
});
factory Folder.fromJson(Map<String, dynamic> parsedJson) {
Iterable i = parsedJson['children'];
return new Folder(
id: parsedJson['id'] ?? '',
title: parsedJson['title'] ?? '',
children: List<Folder>.from(i.map((model) => Folder.fromJson(model)))
);
}
}
This gives me for the children property the following error: The parameter 'children' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Sometimes the Folder doesn't have subfolders, so I wouldn't like to create a #required parameter, just an optional.
I guess you're using the latest version of Dart with the null-safety enabled ?
If that's the case, declaring your children var this way
List<Folder>? children;
should do the trick.
Another solution would be to update your constructor
Folder ({
this.id = 0,
this.title = '',
this.children = []
});
I cannot set a default value this.<List>propertyName = [] in the parameter because the value needs to be const. So I went with not declaring a default value and created a setter/getter.
Here's my example:
[batches.dart]
class Batches{
String? _batchName;
List<Trainees>? _trainees;
// Constructor
Batches({batchName, trainees}) {
this.batchName = batchName;
this.trainees = trainees;
}
// Getter Setter
String? get batchName => this._batchName;
set batchName(String? batchName) => this._batchName = batchName;
List<Trainees>? get trainees => this._trainees;
set trainees(List<Trainees>? traineeList) {
this._trainees = traineeList;
print("Added list of trainees to $batchName!");
}
}
Called the setter function in void main() and then set the existing List batch1_trainees to the setter of the function
[main.dart]
List<Trainees> batch1_trainees = [
Trainee("Trainee Wan"),
Trainee("Trainee Tiu"),
];
Batches batch1 = Batches(batchName: "first_batch");
batch1.trainees = batch1_trainees;
`
Trainees is a class that takes Full_Name as a positional parameter.
If the setter is called, the console should print Added list of trainees to first_batch!
PS.
The getter and setter were necessary in my example because the properties were set to private.

How to setup Moq with Callbacks?

Ok, I have started to look at Moq, so this is a noob question.
I have followed the quick guide, and I am trying to setup a callback to return a specific model:
void Main()
{
var resultData = new MyModel();
var mock = new Mock<IMyClass>();
mock.Setup(x => x.Register(It.IsAny<string>()))
.Returns(new MyModel { Name = "Test" })
.Callback<MyModel>((data) =>
{
resultData = data;
});
var parameter = "123";
var result = mock.Object.Register(parameter);
}
public interface IMyClass
{
MyModel Register(string code);
}
public class MyModel
{
public string Name { get; set; }
}
I get this exception on the call:
ArgumentException: Object of type 'System.String' cannot be converted
to type 'UserQuery+MyModel'.
What am I doing wrong?
The T in the Callback<T> method should match the parameter type of the method being Setup. In other words, Moq is letting you set a callback method with the same parameters as the method being mocked.
I'm not exactly sure what you're trying to do here. If you're just trying to save the return MyModel object from your mocked method, do this:
var returnedModel = new MyModel { Name = "Test" };
mock.Setup(x => x.Register(It.IsAny<string>()))
.Returns(returnedModel);
If you're trying to create a MyModel with the given string parameter, do this:
mock.Setup(x => x.Register(It.IsAny<string>()))
.Returns((string data) => new MyModel { Name = data });

in Dart, how do you use `class` when stored in a variable?

in Dart, you can assign a class to a variable, eg,
var klass = String;
but once assigned, how do you used it?
var str = new klass(); ===> ERROR: malformed type used
once one has a class in a variable, how does one use it to instantiate a new object of that class?
You have to use dart:mirrors.
import 'dart:mirrors';
class A {
A();
A.named(String value);
}
main() {
final t = A;
// same as 'new A()'
final a1 = reflectClass(t).newInstance(const Symbol(''), []).reflectee;
// same as 'new A.named('test')'
final a2 = reflectClass(t).newInstance(#named, ['test']).reflectee;
}