I created one class as Student.
class Student{
int id;
String name;
Student({this.id,this.name});
}
Now I need to print key - id and name
For a proper way to do that you could check my code below. This is how to override the toString().
import 'package:flutter/foundation.dart';
#immutable
class Student{
final int id;
final String name;
const Student({required this.id,required this.name});
#override
String toString() {
return 'Student{id: $id, name: $name}';
}
}
Then you could print like this:
Student student = const Student(id: 1, name: 'John');
print(student);
print(student.id);
print(student.name);
Create a toJson method inside your Student class, and print out your parameters.
class Student{
int id;
String name;
Student({this.id,this.name});
Map<String, dynamic> toJson() => {
if(id!= null) "Id": id,
if(name != null) "Name": name,
};
}
then,
Student exampleStudent= Student(id: '001', name: "john"); //feed values
print(exampleStudent.toJson());
Related
I want a hivemodel class which is contain enum as field but hive is not able to put set value.
CONTACTTYPE is enum:
#freezed
#HiveType(typeId: 7, adapterName: "FriendGroupEntityAdapter")
#freezed
class FriendsGroupEntity with _$FriendsGroupEntity {
const factory FriendsGroupEntity({
#HiveField(0) int userId,
#HiveField(1) #Default(CONTACTTYPE.loop) CONTACTTYPE contactType,
#HiveField(2) String contact,
#HiveField(3) int id,
#HiveField(4) int value,
#HiveField(5) int value2,
#HiveField(6) int value3,
#HiveField(7) int value7,
});
Here CONTACTTYPE.loop is an enum and I want to store it into hive, and got an error which I attach.
Is there any way for enum in hive?
Please follow this approach
import 'package:hive/hive.dart';
part 'myrepresentation.g.dart';
#HiveType(typeId: 1)
class FriendsGroupEntity extends HiveObject {
#HiveType(0)
final String id;
#HiveType(1)
final Foo foo;
MyRepresentation({required this.id, required this.foo});
}
#HiveType(typeId: 2)
enum Foo {
#HiveField(0)
foo,
#HiveField(1)
bar,
}
check this reference link
I have a class with the following attributes in Dart
class StartValue {
final int id;
final String firstName;
final String lastName;
StartValue({this.id, this.firstName, this.lastName})
}
and Ill initiate that classe with the values:
StartValue(
id: 1,
firstName: 'First',
lastName: 'LastName'
)
The question is what kind of validation i need to do to never instance a class StartValue with the NAME = 'First' again? Assuming I can only instantiate the class once with firstName = 'First'.
How do I do an instance validation to verify that each instance does not contain the firstName = "First" ?
I have to do something like:
StartValues.contains("First")
Keep in mind that I have almost 1000 classes instantiated, so I will have to check one by one if the value "First" contains in each class, this is my question
You have to iterate through every class to check if the firstName is taken, but I recommend using the == operator instead of .contains(). Why would you have 1000 instances? Can you put us in context?
Use a class-static Set of all ids seen so far. This will be quick to identify whether an item has already been generated.
Something like:
class Person {
final int id;
final String name;
static var seenIds = <int>{};
Person({
required this.id,
required this.name,
}) {
if (!seenIds.add(id)) throw ArgumentError('id $id already seen');
}
}
Keeping thousands of instances / names in memory is bad design as they are way too many instances / names you don't need at that moment. You go for local sql database like sqflite or you go for cloud database like Cloud Firestore to fetch the user you need and validate it.
If you still want to do it in-memory you can use a factory constructor, a private constructor and a static HashSet to check user instances.
If you need explanation then comment below. Full code example:
import 'dart:collection';
class Person {
final int id;
final String firstName;
final String lastName;
static HashSet<String> allNames = HashSet<String>();
factory Person({
required int id,
required String firstName,
required String lastName,
}) {
if (!allNames.add(firstName)) {
throw ArgumentError("Person with firstname $firstName already exists");
}
return Person._(id: id, firstName: firstName, lastName: lastName);
}
Person._({
required this.id,
required this.firstName,
required this.lastName
});
}
Suppose there are two models User and City
#JsonSerializable()
class User {
int id;
String name;
City? city;
List<Map<String, City>>? listMapCity;
}
#JsonSerializable()
class City {
int id;
String name;
}
Now suppose during API call, we've got a user model but in the city object model, we only get id not name. Something like this
{
"id": 5,
"name": "Matthew",
"city": {
"id": 12
}
}
But due to the default nature of json_serializable and json_annotation.
This JSON is not mapped to the User model, during mapping, it throws the exception.
type Null is not a subtype of type String. (because here name key is missing in city object)
But as we already declared in the User object that City is optional, I wanted that it should parse the User JSON with city and listMapCity to be null.
Any help or solution would be really appreciated, Thank you
You need to set the includeIfNull flag to false to have the autogenerated code handle nulls correctly.
#JsonSerializable(includeIfNull: false)
The property should be declared with a ? as per your example.
You need to have a default constructor on your JsonSerializable User class. Then, if name should be nullable, declare it with a nullable String? name;
Here's the updated User class.
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
#JsonSerializable()
class User {
int id;
String name;
City? city;
List<Map<String, City>>? listMapCity;
User({required this.id, required this.name, this.city, this.listMapCity});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
#JsonSerializable()
class City {
int id;
String name;
City({required this.id, required this.name});
}
New programmer here, I'm trying to add a List object to a list within another class but it keeps giving me an error.I've been stuck on this problem for hours now
void main()
{
List<Hobbies> hobby;
Hobbies hobbies = new Hobbies("Football");
hobby.add(hobbies);
User user1 = new User("Harris", 22, hobby);
print(user1.getAge());
}
class User
{
String name;
int age;
List<Hobbies> hobbies;
User(String name, int age, List<Hobbies> hobbies)
{
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
getAge()
{
print(name);
}
}
class Hobbies
{
String name;
Hobbies(String name)
{
this.name = name;
}
getAge()
{
print(name);
}
}
The error i keep getting
TypeError: C.JSNull_methods.add$1 is not a functionError: TypeError: C.JSNull_methods.add$1 is not a function
You mixed a lot of things here, but let's try to unwrap it all one by one. :)
So few things regarding naming conventions to make your life easier:
Don't use plurals for object names if they are representing one item, and not a list of something.
Always use plurals for property of type list.
Getter methods should always return a type, if you miss that part, you won't see compile time errors your upper project has at the moment trying to print variables instead of returning values, and than again printing in main file for 2nd time...
If you follow those principles, you would get your objects looking like this
class User {
String name;
int age;
List<Hobby> hobbies;
User(String name, int age, List<Hobby> hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
int getAge() => print(name);
}
class Hobby {
String name;
Hobby(String name) {
this.name = name;
}
String getName() => this.name;
}
After this is sorted, let's approach adding data and initialising those objects:
void main() {
List<Hobby> hobbies = [Hobby("Football")];
User user1 = new User("Harris", 22, hobbies);
print(user1.getAge().toString());
}
You need to initialize a List, otherwise it is null and null has no add, so do this:
final hobby = List<Hobbies>();
// or final List<Hobbies> hobby = [];
// or final hobby = <Hobby>[];
Hobbies hobbies = new Hobbies("Football");
hobby.add(hobbies);
final user1 = User("Harris", 22, hobby);
I have class Student and List like below
List<Student> info;
class Student {
final String id;
final String name;
Student({this.id, this.name});
}
and I have some code to add value to List
for (var v; v < count; v++) {
info.add(Student(
id: ....,
name: ....,
));
}
How can I console print detail of value on List<Student> info for test?
Override toString of Student class to make it return the String you want:
class Student {
final String id;
final String name;
Student({this.id, this.name});
#override
String toString() => 'id: $id, name: $name';
}
Then print the list with print(info).
You can just do this
print(info.toString());
to print the whole list.