Use getters and setters to create string from 1-7 integers - dart

I'm trying to take a 1-7 integer value and print out a day for each value with an enum.
I get an error in the class mapping from firestore, "isn't a field in the enclosing class"
So if 1 is passed in then "Monday" is given
if 2 is passed in then "Tuesday" is given
enum _Days {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
class HeadingItem implements ListItem {
String _weekday;
final int time;
final DocumentReference reference;
set day(int weekday) {
var value = _Days.values[weekday - 1].toString();
var idx = value.indexOf(".") + 1;
var result = value.substring(idx, value.length);
_weekday = result;
}
String get day {
return _weekday;
}
HeadingItem.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['day'] != null),
assert(map['time'] != null),
day = map['day'], // 'day' isn't a field in the enclosing class <--- this is the error that im stuck on...
time = map['time'];
HeadingItem.fromSnapshot(DocumentSnapshot snapshot) : this.fromMap(snapshot.data, reference: snapshot.reference);
}

Change
String get day {
return _weekday;
}
to this
String day = _weekday;

Notice that in your code, day is technically a set of methods of this that allows us to work with day as if it were a member of this; day is not actually a member.
Thus, in order for your initializer list to work as you intended it to, it would already need to have access to this in order to provide the functionality you want (for example, to set the value of the internal member _weekday).
However, as mentioned in the Language Tour of Dart in the section on Initializer Lists, the initializer list does not have access to this. Rather we should see the initializer list as values to assign to members of this during the instantiation.

Related

Dart Object instantiating

I'm very new to programming and Dart. I was wondering why you put Response in front of the variable response. Also why do we use Datetime object in front of the variable 'now?' I believe when you want to instantiate, you write Datetime now = Datetime(); But it was written something else for the variable. What does it mean? Thank you very much in advance!
void getTime() async{
Response response = await get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
Map data = jsonDecode(response.body);
// get properties from data
String datetime = data['datetime'];
String offset = data['utc_offset'].substring(1,3);
//create DateTime object
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset)));
print(now);
}
Ok, let's break this down:
Response response = await
get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
A variable declaration in Dart looks like this:
<Type> <name> [= <value>];
So in your case Response is the type of the variable, response is the name of the variable and get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London')) is the value of the variable (actually get(...) is a future, and the future's response is the value, that's why the await keyword is there, but that's not important.)
Sidenote, you can actually use the var keyword to skip the <Type> part of the declaration:
int myFunction(a, b) => a+b;
int x = myFunction(1,2);
Above, we know myFunction returns an int, and the variable x is equal to the result of myFunction, so it must also be an int, we can use the var keyword to skip writing int then:
int myFunction(a, b) => a+b;
var x = myFunction(1,2);
Of course, here there isn't that big a difference between writing int and var, but when your type is something like List<Map<String, List<int>>> it is quite nice to be able to skip writing that over and over
Now for this line:
DateTime now = DateTime.parse(datetime);
We already know that the first DateTime tells us what type the variable is, and we know that now is the name of the variable, we also know that the variable's value is DateTime.parse(datetime) because it is what goes after the = sign, but we still don't know what DateTime.parse(datetime) means.
Classes can have static and non-static methods, a static method is a method that gets called on a class, while a non-static method gets called on an object. Most method calls ever are non-static, look at this example:
class Car {
void accelerate() {
// some method to increase the speed of the car
}
void decelerate() {
// some method to decrease the speed of the car
}
Car buyCar(int maxCost) {
// some method to buy a new car
}
}
void main() {
Car car = Car();
car.accelerate();
car.decelerate();
Car otherCar = car.buyCar(100000000);
}
Above, the method accelerate and decelerate are instance methods and that makes sense because they probably affect some statistics of the car (like current speed), buyCar is also an instance method, but if you think about it, it shouldn't be, it doesn't affect your current car if you buy a new one and also you shouldn't need to have a car object to buy another one in the first place. So let's make that last method static:
class Car {
void accelerate() {
// some method to increase the speed of the car
}
void decelerate() {
// some method to decrease the speed of the car
}
static Car buyCar(int maxCost) {
// some method to buy a new car
}
}
It is as simple as adding the static keyword, now instead of having to do this:
Car myOldCar = Car();
Car myNewCar = myOldCar.buyCar(100000000);
we can just do this:
Car myNewCar = Car.buyCar(100000000);
looks familiar?
That's right parse is a static method on DateTime class, it takes a string that looks like this: 2012-02-27 13:27:00.123456789z and returns a DateTime object.
So to recap:
Response response = await
get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
Response is the type of the variable, response is its name and get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London')) is a method that returns a Response object.
DateTime now = DateTime.parse(datetime);
Similarly DateTime is the type, now is the name and DateTime.parse is a static method that parses a string and makes a DateTime object, in this case the string is datetime, which was declared as being equal to data['datetime'].
If you want to understand better how the parse method works, here is the DateTime parse documentation

How to print value of an enum? [duplicate]

Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the name of the enum as a string such as can be done with Java but cannot.
For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"
enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');
Am I correct that to get just 'MONDAY' I will need to parse the string?
Dart 2.7 comes with new feature called Extension methods. Now you can write your own methods for Enum as simple as that!
enum Day { monday, tuesday }
extension ParseToString on Day {
String toShortString() {
return this.toString().split('.').last;
}
}
main() {
Day monday = Day.monday;
print(monday.toShortString()); //prints 'monday'
}
Bit shorter:
String day = theDay.toString().split('.').last;
Update Dart 2.15:
enum Day {
monday,
tuesday,
}
You can use name property on the enum.
String monday = Day.monday.name; // 'monday'
Old solution:
1. Direct way:
var dayInString = describeEnum(Day.monday);
print(dayInString); // prints 'monday'
2. Using Extension:
extension DayEx on Day {
String get name => describeEnum(this);
}
You can use it like:
void main() {
Day monday = Day.monday;
print(monday.name); // 'monday'
}
It used to be correct that the only way to get the source name
of the enum value was through the toString method which returns "day.MONDAY", and not the more useful "MONDAY".
Since Dart 2.15, enums have exposed a extension getter which returns just the source name, so day.MONDAY.name == "MONDAY".
Since Dart 2.17, you can also add your own members to enum declarations, and choose to provide another name for
a value than justits source name, e.g., with a more appropriate capitalization:
enum Day {
monday("Monday"),
tuesday("Tuesday"),
// ...
saturday("Saturday");
sunday("Sunday");
final String name;
Day(this.name);
// And other members too.
bool get isWorkday => index < saturday.index;
}
Then you get Day.sunday.name == "Sunday" (hiding the extension name getter which would return "sunday").
Before these features, you could only get the name from the toString string, extracting the rest of the string as:
day theDay = day.MONDAY;
print(theDay.toString().substring(theDay.toString().indexOf('.') + 1));
which was admittedly hardly convenient.
Another way to get the enum name as a string, one which is shorter, but also less efficient because it creates an unnecessary string for first part of the string too, was:
theDay.toString().split('.').last
If performance doesn't matter, that's probably what I'd write, just for brevity.
If you want to iterate all the values, you can do it using day.values:
for (day theDay in day.values) {
print(theDay);
}
Simplest way to get the name of an enum is a standard method from the flutter/foundation.dart
describeEnum(enumObject)
enum Day {
monday, tuesday, wednesday, thursday, friday, saturday, sunday
}
void validateDescribeEnum() {
assert(Day.monday.toString() == 'Day.monday');
assert(describeEnum(Day.monday) == 'monday');
}
enum day {MONDAY, TUESDAY}
print( 'Today is ${describeEnum(day.MONDAY)}' );
console output: Today is MONDAY
There is a more elegant solution:
enum SomeStatus {
element1,
element2,
element3,
element4,
}
const Map<SomeStatus, String> SomeStatusName = {
SomeStatus.element1: "Element 1",
SomeStatus.element2: "Element 2",
SomeStatus.element3: "Element 3",
SomeStatus.element4: "Element 4",
};
print(SomeStatusName[SomeStatus.element2]) // prints: "Element 2"
Sometimes I need to separate ui-value and real-value, so I defined keys and values using Map. This way, we have more flexiblity. And by using extension (since Dart 2.7), I made a method to read its key and value.
enum Status {
progess,
done,
}
extension StatusExt on Status {
static const Map<Status, String> keys = {
Status.progess: 'progess',
Status.done: 'done',
};
static const Map<Status, String> values = {
Status.progess: 'In Progress',
Status.done: 'Well done',
};
String get key => keys[this];
String get value => values[this];
// NEW
static Status fromRaw(String raw) => keys.entries
.firstWhere((e) => e.value == raw, orElse: () => null)
?.key;
}
// usage 1
Status status = Status.done;
String statusKey = status.key; // done
String statusValue = status.value; // Well done
// usage 2 (easy to make key and value list)
List<Status> statuses = Status.values;
List<String> statusKeys = statuses.map((e) => e.key).toList();
List<String> statusValues = statuses.map((e) => e.value).toList();
// usage 3. create Status enum from string.
Status done1 = StatusExt.fromRaw('done') // Status.done
Status done2 = StatusExt.fromRaw('dude') // null
With Dart 2.17 we now have general support for members on enums. That means we can add fields holding state, constructors that set that state, methods with functionality, and even override existing members.
Example:
enum Day {
MONDAY("Monday"),
TUESDAY("Tuesday");
const Day(this.text);
final String text;
}
Output:
void main() {
const day = Day.MONDAY;
print(day.text); /// Monday
}
For above functionality override dart version like below which target 2.17 and greater
environment:
sdk: ">=2.17.0 <3.0.0"
I got so over this I made a package:
https://pub.dev/packages/enum_to_string
Also has a handy function that takes enum.ValueOne and parses it to "Value one"
Its a simple little library but its unit tested and I welcome any additions for edge cases.
I use the functions below to get the name of the enum value and, vise versa, the enum value by the name:
String enumValueToString(Object o) => o.toString().split('.').last;
T enumValueFromString<T>(String key, Iterable<T> values) => values.firstWhere(
(v) => v != null && key == enumValueToString(v),
orElse: () => null,
);
When using Dart 2.7 and newer, extension methods would work here (as well as for any other Objects):
extension EnumX on Object {
String asString() => toString().split('.').last;
}
The implementation above is not dependant on the specific enums.
Usage examples:
enum Fruits {avocado, banana, orange}
...
final banana = enumValueFromString('banana', Fruits.values);
print(enumValueToString(banana)); // prints: "banana"
print(banana.asString()); // prints: "banana"
Edit from 2020-04-05: Added nullability checks. values parameter could be Iterable, not necessarily List. Added extensions method implementation. Removed <Fruits> annotation from the example to show that the class name duplication is not required.
I use structure like below:
abstract class Strings {
static const angry = "Dammit!";
static const happy = "Yay!";
static const sad = "QQ";
}
Dart 2.15 includes an extension to make this easy:
enum day {MONDAY, TUESDAY}
print( 'Today is ${day.MONDAY.name}');
Until the changes in https://github.com/dart-lang/sdk/commit/18f37dd8f3db6486f785b2c42a48dfa82de0948b are rolled out to a stable version of Dart, the other clever but more complex answers here are very useful.
One more way:
enum Length {
TEN,
TWENTY,
THIRTY,
NONE,
}
extension LengthValue on Length {
static const _values = [10, 20, 30, 0];
int get value => _values[this.index];
}
since dart 2.15 just use ".name"
enum day {monday, tuesday}
print( 'Today is ${day.monday.name}');
My approach is not fundamentally different, but might be slightly more convenient in some cases:
enum Day {
monday,
tuesday,
}
String dayToString(Day d) {
return '$d'.split('.').last;
}
In Dart, you cannot customize an enum's toString method, so I think this helper function workaround is necessary and it's one of the best approaches. If you wanted to be more correct in this case, you could make the first letter of the returned string uppercase.
You could also add a dayFromString function
Day dayFromString(String s) {
return Day.values.firstWhere((v) => dayToString(v) == s);
}
Example usage:
void main() {
Day today = Day.monday;
print('Today is: ${dayToString(today)}');
Day tomorrow = dayFromString("tuesday");
print(tomorrow is Day);
}
enum day {MONDAY, TUESDAY}
print(day.toString().split('.')[1]);
OR
print(day.toString().split('.').last);
Create a class to help:
class Enum {
Enum._();
static String name(value) {
return value.toString().split('.').last;
}
}
and call:
Enum.name(myEnumValue);
One of the good ways I found in the answer is
String day = theDay.toString().split('.').last;
But I would not suggest doing this as dart provide us a better way.
Define an extension for the enum, may be in the same file as:
enum Day {
monday, tuesday, wednesday, thursday, friday, saturday, sunday
}
extension DayExtension on Day {
String get value => describeEnum(this);
}
You need to do import 'package:flutter/foundation.dart'; for this.
I had the same problem in one of my projects and existing solutions were not very clean and it didn't support advanced features like json serialization/deserialization.
Flutter natively doesn't currently support enum with values, however, I managed to develop a helper package Vnum using class and reflectors implementation to overcome this issue.
Address to the repository:
https://github.com/AmirKamali/Flutter_Vnum
To answer your problem using Vnum, you could implement your code as below:
#VnumDefinition
class Visibility extends Vnum<String> {
static const VISIBLE = const Visibility.define("VISIBLE");
static const COLLAPSED = const Visibility.define("COLLAPSED");
static const HIDDEN = const Visibility.define("HIDDEN");
const Visibility.define(String fromValue) : super.define(fromValue);
factory Visibility(String value) => Vnum.fromValue(value,Visibility);
}
You can use it like :
var visibility = Visibility('COLLAPSED');
print(visibility.value);
There's more documentation in the github repo, hope it helps you out.
Instead of defining extension for every enum, we can define extension on object and get access to .enumValue from any enum.
void main() {
// ❌ Without Extension ❌
print(Countries.Cote_d_Ivoire.toString().split('.').last.replaceAll("_", " ")); // Cote d Ivoire
print(Movies.Romance.toString().split('.').last.replaceAll("_", " ")); //Romance
// ✅ With Extension ✅
print(Countries.Cote_d_Ivoire.enumValue); // Cote d Ivoire
print(Movies.Romance.enumValue); //Romance
}
enum Countries { United_States, United_Kingdom, Germany, Japan, Cote_d_Ivoire }
enum Movies { Romance, Science_Fiction, Romantic_Comedy, Martial_arts }
extension PrettyEnum on Object {
String get enumValue => this.toString().split('.').last.replaceAll("_", " ");
}
With this, you can even define multi-word enum where words are separated by _(underscore) in its name.
As from Dart 2.15, you can get enum value from
print(MyEnum.one.name);
// and for getting enum from value you use
print(MyEnum.values.byName('two');
try this solution:
extension EnumValueToString on Enum {
String valueAsString() {
return describeEnum(this);
}
}
how to used it:
enum.valueAsString()
dart 2.15 is now supporting this
you can just type
print(day.MONDAY.name); //gives you: MONDAY
Since Dart 2.15, we can just do Day.monday.name, where
enum Day { monday, tuesday }
As from Dart version 2.15, you can access the String value of an enum constant using .name:
enum day {MONDAY, TUESDAY}
void main() {
print('Today is ${day.MONDAY.name}');
// Outputs: Today is MONDAY
}
You can read in detail about all the enum improvements in the official Dart 2.15 release blog post.
as of dart 2.15 you can use .name to get the name of enum elements.
enum day {MONDAY, TUESDAY}
print(day.MONDAY.name); // prints MONDAY
Dart version 2.15 has introduced name property on enums.
Example
void main() {
MyEnum.values.forEach((e) => print(e.name));
}
enum MyEnum { value1, Value2, VALUE2 }
Output:
value1
Value2
VALUE2
For those who require enum with values use this approach as Dart doesn't support this:
class MyEnumClass {
static String get KEY_1 => 'value 1';
static String get KEY_2 => 'value 2';
static String get KEY_3 => 'value 3';
...
}
// Usage:
print(MyEnumClass.KEY_1); // value 1
print(MyEnumClass.KEY_2); // value 2
print(MyEnumClass.KEY_3); // value 3
...
And sure you may put whatever types you need.
now with null safety it looks like this
String enumToString(Object? o) => o != null ? o.toString().split('.').last : '';
T? enumFromString<T>(String key, List<T> values) {
try {
return values.firstWhere((v) => key == enumToString(v));
} catch(e) {
return null;
}
}

Attempting to map dates to index in ElasticSearch

I am using ElasticSearch and attempting to create an index with a class that has a dynamic type property in it. This property may have strings or dates in it. When indexing, I have been using the code below:
dynamic instance = MyObject.GetDynamicJson();
var indexResponse = client.Index((object) instance, i=>i
.Index("myIndex")
.Type("MyObject")
);
Here's the code for GetDynamicJson().
MyObject has only Name and Value as properties. (apologies, I've had issues in the past with Elastic choking on json without all the quotes, which I have escaped with \ characters):
String json = "{ \"Name\":\" + Name + "\",\"DateValue\":\"";
try {
var date = DateTime.parse(Value);
json += DateTime.ToString("yyyy/MM/dd HH:mm:ss Z") + "\", \"Value\":\"\"}";
} catch { //If the DateTime parse fails, DateValue is empty and I'll have text in Value
json += "\",\"Value\":\"" + Value + "\"}";
}
return json;
For some reason it doesn't seem to like the string in DateValue and I definitely don't know why it's leaving out that property entirely in the error:
For whatever reason, ElasticSearch is completely dumping the DateValue property, doesn't seem to see the DateValue property at all.
I'm getting the error:
{"name":"CreatedDate","value":"2017-11-07T13:37:11.4340238-06:00"}
[indices:data/write/bulk[s][p]]"}],"type":"class_cast_exception","reason":"org.elasticsearch.index.mapper.TextFieldMapper cannot be cast to org.elasticsearch.index.mapper.DateFieldMapper"},"status":500
Later note: I have changed the index creator method to update the mapping. I added a third field to the Object, so now it has properties: Name, Value, DateValue:
public static void CreateRecordsIndex(ElasticClient client)
{
client.CreateIndex("myIndex", i => i
.Settings(s => s
.NumberOfShards(2)
.NumberOfReplicas(0)
)
.Mappings(x => x
.Map<MyObject>(m => m.AutoMap())));
}
Now, it is successfully mapping and creating a property each time, but it still seems to drop the property I am sending it in the json. It just sets them all to the default datetime: "dateValue": "0001-01-01T00:00:00". This is strange, because when making the dynamic instance I send to Elastic, I use only the MyObject.GetDynamicJson() method to build it. I no longer get the mapping error, but Elastic still seems oblivious to "dateValue":"some date here" in the object when it is set.
OK, I got rid of the dynamic object type (ultimately I wasn't actually getting data from the json method, I had a typo and Elastic was getting the original object directly - it's a wonder it was still handling it). So I let Elastic do the parse using its mapping. In order to do that, I first updated MyObject to include multiple properties, one for each type the incoming property could be (I am only handling text and dates in this case). For the DateValue property of MyObject, I have this:
public DateTime DateValue {
get
{
try
{
return DateTime.Parse(Value);
} catch
{
return new DateTime();
}
}
set
{
try {
DateValue = value;
} catch
{
DateValue = new DateTime();
}
}
}
Now, if Value is a date, my DateValue field will be set. Otherwise it'll have the default date (a very early date "0001-01-01T00:00:00"). This way, I can later search both for text against that dynamic field, or if a date is set, I can do date and date range queries against it (technically they end up in two different fields, but coming from the same injested data).
Key to this is having the index mapping setup, as you can see in this method from the question:
public static void CreateRecordsIndex(ElasticClient client)
{
client.CreateIndex("myIndex", i => i
.Settings(s => s
.NumberOfShards(2)
.NumberOfReplicas(0)
)
.Mappings(x => x
.Map<MyObject>(m => m.AutoMap())));
}
In order to recreate the index with the updated MyObject, I did this:
if (client.IndexExists("myIndex").Exists)
{
client.DeleteIndex("myIndex");
CreateRecordsIndex(client); //Goes to the method above
}

Get the object with the most recent date

I have an array of objects of type Thing:
class Thing: NSObject {
var data: String
var type: String
var created: NSDate
}
These things have an NSDate property called created. My aim is to write a function that reads the created property of every thing in the array and returns the thing that has the most recent date. The function looks like this:
public func getLastSwipe(list: Array<Thing>) -> Thing {
return someThing
}
Another approach is using Swift's .max, like this:
dates.max(by: <)
The following is my old answer. The above is updated in feb 2023.
let mostRecentDate = dates.max(by: {
$0.timeIntervalSinceReferenceDate < $1.timeIntervalSinceReferenceDate
})
This is the most performant solution I've found.
Returns the sequence’s most recent date if the sequence is not empty; otherwise, nil.
You could use reduce if you wanted. This will find the object with the highest timestamp.
var mostRecent = list.reduce(list[0], { $0.created.timeIntervalSince1970 > $1.created.timeIntervalSince1970 ? $0 : $1 } )
If your dates are not all in the past, you'll have to also compare against the current date to determine a cutoff. If your dates are all in the future, you'll want to switch the > to < to find the next future date (lowest timestamp).
You can sort the array, then find the first/last element. For example...
let objects: [Thing] = ... //Set the array
let mostResent = array.sorted { (firstThing, secondThing) -> Bool in
firstThing.created.timeIntervalSince1970 > secondThing.created.timeIntervalSince1970
}.first
This will return the most resent Thing as an Optional (because there is no guarantee that the array is not empty. If you know that the array is not empty, then you can end that line with .first!

How to set formula in grails domain class?

I am trying to write formula in my domain class which helps me in creating criteria.
class MyClass {
//some fields
Date appointmentTime
String ddmmyy
int year
int month
int day
static transients = [
'ddmmyy',
'year',
'month',
'day'
]
static mapping= {
ddmmyy formula('DATE_FORMAT(appointmentTime)')
year formula('YEAR(appointmentTime)')
month formula('MONTH(appointmentTime)')
day formula('DAYOFMONTH(appointmentTime)')
}
}
Whenever I am trying to use this fields in my criteria it throws error i.e. can not resolve property 'ddmmyy' of 'myClass'.
MyCriteria is:
Date myDate = Calender.instance.time
def results = MyClass.createcriteria().list{
lt('appointmentTime', date+1)
ge('appointmentTime', date)
projections {
groupProperty('ddmmyy')
count('id')
}
}
Any idea why I am getting an exception for this?
You need to make these fields non transient to use in criteria. See reference document
http://gorm.grails.org/6.1.x/hibernate/manual/#derivedProperties

Resources