Create hive object with auto increment integer value - flutter

How to create hive object that includes an id field with auto increment integer value?
This is my hive object class and id always is -1. How should I fix it?
import 'package:hive_flutter/adapters.dart';
part 'reminder.g.dart';
#HiveType(typeId : 2 )
class Reminder extends HiveObject {
int id = -1;
#HiveField(0)
String title = '';
#HiveField(1)
String body = '';
#HiveField(2)
String dateFancyString = '' ;
#HiveField(3)
String timeFancyString = '' ;
#HiveField(4)
DateTime dateTime = DateTime.now();
}

Related

Number of days between two Instants doesn't change when changing a specific end date

I have a class that I use to get the number of days between 2 Instants :
public static Long getDaysBetween(final Instant startInstant, final Instant endInstant) {
final ZonedDateTime startDate = startInstant.atZone(ZoneId.systemDefault());
final ZonedDateTime endDate = endInstant.atZone(ZoneId.systemDefault());
return ChronoUnit.DAYS.between(startDate, endDate);
}
And the corresponding test class
class WeekCalculatorTest {
#Test
void givenStartAndEndInstant_whenCalculatingTheNumberOfDaysBetween_thenTheResultShouldBe() {
final String start = "2022-09-01T00:00:00Z";
final String end = "2022-10-31T00:00:00Z";
final Instant startInstant = Instant.parse(start);
final Instant endInstant = Instant.parse(end);
assertThat(WeekCalculator.getDaysBetween(startInstant, endInstant), is(59L));
}
}
I don't understand why when I change the end variable to final String end = "2022-10-30T00:00:00Z";, my test is still passing.

final variables can't be reassigned, but the object can be mutated in flutter

https://stackoverflow.com/a/55990137/462608
comment:
"Can't be changed after initialized" is ambiguous. final variables can't be reassigned, but the object can be mutated. –
jamesdlin
Feb 19 at 17:43
and https://stackoverflow.com/a/50431087/462608
a final variable's value cannot be changed. final modifies variables
What do both these statements mean? Please give examples.
Consider the following class:
class SampleObject {
int id;
String value;
SampleObject(this.id, this.value);
}
final variable can't be reassigned:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// The final variable 'obj1' can only be set once
obj1 = SampleObject(1, "value2");
}
But the object property can be changed (is mutable):
void main() {
final obj1 = SampleObject(1, "value1");
obj1.value = "value2";
print(obj1.value);
}
But it becomes an immutable object if you set all the property in the class to final:
class SampleObject {
final int id;
final String value;
SampleObject(this.id, this.value);
}
where it gives error when you're trying to reassign a value to its property:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// 'value' can't be used as a setter because it's final.
// Try finding a different setter, or making 'value' non-final
obj1.value = "value2";
}
Imagine the example below:
void main() {
final student = Student('Salih', 29);
print('Student before $student');
student.age = 30;
print('Student after $student');
}
class Student {
Student(this.name, this.age);
final String name;
int age;
#override
String toString() => 'Age is $age and name is $name';
}
One of the fields of the Student object is mutable. This way we can reassign it. What others mean above is that, the object reference of the final variables will be assigned first but internals of the object can be changed.
In our example, final would be preventing to re-assign something to student object but it will not prevent us to re-assign a value within the object.
You can run the code on dartpad.dev above and see the result as follows:
Student before Age is 29 and name is Salih
Student after Age is 30 and name is Salih

Correct declaring of a class in Dart

I am new to dart and I have some basicaly question to the language itself.
During the last days I started with classes in dart.
Now I have a short question about how to declare a class correct.
void main() {
Book harryPotter =
Book(title: "Goblet of Fire", author: "J. K. Rolling", pageCount: 300);
print(harryPotter._title); // 1 -> print "A" to the console
print(harryPotter._author); // 2 -> LateInitializationError: Field '_author#18448617' has not been initialized.
}
class Book {
String _title = "A";
late String _author;
late int _pageCount;
Book(
{required String title,
required String author,
required int pageCount}); // 3
}
Why can I access to the variable even if it's set to private?
Why does the late keyword throw an error, the variable is set during the constructor call?
Do I need to write in the constructor "Book({required String this.title});", or "Book({required String title});" like in the example? If it doesn't matter, why?
Thanks for helping!
Benjamin
Your constructor is not initializing the variables!
It should be:
Book({required String title, required String author, required int pageCount})
: _title = title,
_author = author,
_pageCount = pageCount;
Without that, the _author field is not set at all, and reading an unset late field is an error.
You can't use this.something because the fields have private names (_author) and named parameters cannot have private names. Otherwise that would have been the correct approach. Instead you need to have public-named parameters and then use the value to initialize the field in an initializer list.
With that change, the fields also don't need to be late and can instead be final:
class Book {
final String _title;
final String _author;
final int _pageCount;
Book({required String title, required String author, required int pageCount})
: _title = title,
_author = author,
_pageCount = pageCount;
}
You can access the private variables from inside the same library because Dart privacy is library based.

Why many to one with backlink not allowed in objectbox-dart?

I have this structure:
#JsonSerializable()
class Media {
#Id(assignable: true)
int id = 0;
int lid = 0;
String url = '';
String? title;
}
#Entity()
class NewsPicture extends Media {
#override
#Id(assignable: true)
int id = 0;
#Backlink('newsPicture')
final news = ToOne<News>();
}
#JsonSerializable(explicitToJson: true)
#Entity()
class News extends Data<News> implements DataInterface<News> {
#Id(assignable: true)
#JsonKey(defaultValue: 0)
int lid = 0;
final Picture = ToMany<NewsPicture>();
}
and at the generation process, the objectbox_generator:resolver gives me this error message:
invalid use of #Backlink() annotation - may only be used on a ToMany<>
field
Why is it not allowed? What am I missing?
It's not supported in that direction because it's not really needed (doesn't help with anything), you can just flip the direction/change the place where the relation is stored. Also, ToOne relations are more efficient to store, because they're just a single field in a database, while a standalone ToMany relations require an intermediate "mapping table".
If you update your model like this, it's going to work and you won't see a difference in the way how you can work with it in your app:
#Entity()
class NewsPicture extends Media {
#override
#Id(assignable: true)
int id = 0;
final news = ToOne<News>();
}
#JsonSerializable(explicitToJson: true)
#Entity()
class News extends Data<News> implements DataInterface<News> {
#Id(assignable: true)
#JsonKey(defaultValue: 0)
int lid = 0;
#Backlink()
final Picture = ToMany<NewsPicture>();
}

incompatible types found : double

i am trying to write a program, and the rest of the code so far works but i am getting a incompatible types found : double required :Grocery Item in line 38. Can anyone help me in explaining why I am receiving this error and how to correct it? Thank you. here is my code:
import java.util.Scanner;
public class GroceryList {
private GroceryItem[]groceryArr; //ARRAY HOLDS GROCERY ITEM OBJECTS
private int numItems;
private String date;
private String storeName;
public GroceryList(String inputDate, String inputName) {
//FILL IN CODE HERE
// CREATE ARRAY, INITIALIZE FIELDS
groceryArr = new GroceryItem[10];
numItems = 0;
}
public void load() {
Scanner keyboard = new Scanner(System.in);
double sum = 0;
System.out.println ("Enter the trip date and then hit return:");
date = keyboard.next();
keyboard.nextLine();
System.out.println("Enter the store name and then hit return:");
storeName = keyboard.next();
keyboard.nextLine();
double number = keyboard.nextDouble();
//NEED TO PROMPT USER FOR, AND READ IN THE DATE AND STORE NAME.
System.out.println("Enter each item bought and the price (then return).");
System.out.println("Terminate with an item with a negative price.");
number = keyboard.nextDouble();
while (number >= 0 && numItems < groceryArr.length) {
groceryArr[numItems] = number;
numItems++;
sum += number;
System.out.println("Enter each item bought and the price (then return).");
System.out.println("Terminate with an item with a negative price.");
number = keyboard.nextDouble();
}
/*
//READ IN AND STORE EACH ITEM. STORE NUMBER OF ITEMS
}
private GroceryItem computeTotalCost() {
//add code here
}
public void print() {
\\call computeTOtalCost
}
*/
}
}
"groceryArr[numItems] = number;"
groceryArr[numItems] is an instance of GroceryItem() - 'number' is a double
You need a double variable in your GroceryItem() object to store the 'number' value.