How does the combiner actually work?
Stream<bool> get isValid => Rx.combineLatest2(name1, mobile1, (name2, mobile2) => true);
If name1 and mobile1 are streams, then what are the types of name2 and mobile2 in brackets?
In your example, name2 and mobile2 refer to the latest content that was emitted by the streams name1 and mobile1. So your question - the types of name2 and mobile2 - depend on the streams that you give it.
I think calling them name1 and name2 actually kind of makes it a bit confusing, and perhaps it would make more sense to think of it like this:
Rx.combineLatest2(nameStream, mobileStream, (name, mobile) => ... )
To give a concrete example, imagine that name is a String and mobile is int. And imagine that what you want is a Stream of your own class called Person which has the parameter name and mobile like this:
class Person {
String name;
int mobile;
Person({required this.name, required this.person});
}
You could combine your latest name and latest mobile to get a Stream<Person> like this:
Stream<Person> get person =>
Rx.combineLatest2(
nameStream, mobileStream, (name, mobile) =>
Person(name: name, mobile: mobile));
where:
nameStream is of type Stream<String>
mobileStream is of type Stream<int>
name is of type String
mobile is of type int
and the get function person returns Stream<Person>
You can specify your class types in the function like this:
Stream<Person> get person =>
Rx.combineLatest2<String, int, Person>(
nameStream, mobileStream, (name, mobile) =>
Person(name: name, mobile: mobile));
Related
I'm new at Dart and I'm taking a course but I don't know if I'm doing something wrong at this particular lesson. I have almost the exact code as my instructor, yet I get an Error instead of a "null" result. This is the code:
import 'package:hello_dart/hello_dart.dart' as hello_dart;
// we can also add exceptions on the parameters using "[]"
//
void main(List<String> arguments) {
var name = sayHello("Pink", "Unicorn");
print(name);
}
String sayHello(String name, String lastName, [int age]) => "$name "
"$lastName $age";
The idea of this lesson is to create exceptions on the function's parameters. On this example, he adds [] on "int age" to add an exception and erases "$age". With that he gets "Pink Unicorn null" as a result.
But I get instead this error:
The parameter 'age' can't have a value of 'null' because of its type 'int', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
String sayHello(String name, String lastName, [int age])
^^^
The course is at least four years old, so maybe there was an update where Dart no longer gives a "null" result to an "int" value ? or am I doing something wrong ? https://prnt.sc/cq-YmQgPVx1R
Yes, this course is outdated, it missed dart-null-safety.
Those are optional positional parameters. Please do not call that "exception", since "exception" is a word generally used for something totally unrelated in almost all programming languages including Dart.
Since an int can be longer be null, your optional positional parameter needs to be of type int? to be able to have null as a value.
So this:
void main(List<String> arguments) {
var name = sayHello("Pink", "Unicorn");
print(name);
}
String sayHello(String name, String lastName, [int? age]) => "$name "
"$lastName $age";
Will produce the output:
Pink Unicorn null
For more information on "null safety" and why it's a really great feature, see https://dart.dev/null-safety
Try to use tutorials from the last year at least. Flutter and Dart change fast, to the better, and you should not start learning something only to have outdated knowledge when you are done. Make sure you are learning from a source that is current.
I have the table:
#Entity()
#JsonSerializable()
class DateTimeStruct {
#JsonKey(ignore: true)
int id = 0;
DateTime time = DateTime.now();
String? title;
DateTimeStruct();
factory DateTimeStruct.fromJson(Map<String, dynamic> json) => _$DateTimeStructFromJson(json);
Map<String, dynamic> toJson() => _$DateTimeStructToJson(this);
}
and
#JsonSerializable(explicitToJson: true)
#Entity()
class Event {
final Time = ToMany<DateTimeStruct>();
}
When I try to query related table with link, like this:
Store.box<Event>().query().link(Event_.Time,
DateTimeStruct_.time.greaterOrEqual(DateTime.now().millisecondsSinceEpoch));
I get the
The argument type 'QueryRelationMany<Event, DateTimeStruct>' can't be assigned to the parameter type 'QueryRelationProperty<Event, DateTimeStruct>'
error message.
Second problem: DateTimeStruct_.time resolved as QueryIntegerProperty<DateTimeStruct> time, but it is a DateTime. Has it converted to integer in database?
Given entities won't work with pub run build_runner build because Event is missing an id
You're using ToMany relations - you'd only want to do that if you want to store multiple DateTimeStruct for each Event - just making sure you're aware. If it's fine to only have a single time per event (which, conceptually, sounds right to me), use ToOne.
With ToMany, you need to link using .linkMany() instead of .link() - that's where the compilation error comes from.
Yes Dart DateTime objects are stored as a millisecond timestamp (unless you specify otherwise using #Property(type: PropertyType.dateNano) annotation). You need to query them as such - you seem to be doing that correctly.
I want to access to a property by the name si string format.
If I have a class like that:
class PrefsState {
String a;
PrefsState({
this.a,
})
How can I do something like that:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test[key]);
Of course is not working. There is a way to do that in Dart ?
Unfortunately, you cannot use reflection/mirrors in flutter.
What you can do, which is tedious, is use maps.
class PrefsState {
String a;
const PrefsState({ this.a, });
dynamic getProp(String key) => <String, dynamic>{
'a' : a,
}[key];
}
It's probably better to build the map in the constructor, but if you want const constructors then you'll have to settle for this. Likely won't make much of a difference unless you have a million parameters anyway. Then you use it like so:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test.getProp(key));
I don't think there is a less cumbersome way of doing this, but would love to be proven wrong :-)
You can do it with mirrors, but mirrors don't work in dart2js or flutter. You can use code builders to get at this, but the real question is what is your need for this?
I wonder, if a dart or flutter method exists, which returns complete type information about the structure of a variable's value as a string.
E.g., if some print( someValue.toString() ); emits this
{"user":"userName","state":"valid"}
I don't know if it is a Map or a String.
But how do I get a string, which describes a variable's value / structure?
Something, that's like PHP's print_r(), which print stuff like this:
Array
(
[a] => Apfel
[b] => Banane
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
There is nothing like print_r() available natively in Dart.
However, it would be possible to use the following functionalities to build e.g. a function like print_r() from PHP.
You can evaluate the type of someValue using runtimeType.
String someValueType = someValue.runtimeType.toString();
String someValueString = someValue.toString();
If you want to compare, you can also use is. More on that here.
Dart is a strongly typed language, which means that you could also enforce types (List a; String b), which makes a function like print_r() redundant for Dart.
If it is about server-side code you can use reflection to create a function that produces such an output for every value.
If it is about your own classes, you can implement toString() to make the objects render themselves this way when they are printed
class Person {
Foo(this.firstName, this.lastName);
String firstName;
String lastName;
#override
String toString() => '''
firstName: $firstName
lastName: $lastName
''';
}
print(new Person('John', 'Doe'));
Best way to do is
print(”$someValue“);
It will return a structured string which similar to JSON.
I have a simple Address domain object that has the following string fields: line1, line2, city, state, zipCode. I'd like to setup the toString() method to display a formatted string skipping any fields that are null.
For example, an Address that does not have a line2 should be displayed as: , , (e.g. "1234 My Street, Albuquerque, NM, 12345" rather than "1234 My Street, null, Albuquerque, NM, 12345").
Is there a slick way to do this in groovy other than the following? Also, since Grails generates code that uses the toString() to represent domain objects on the web pages, should I continue to use toString() for display purposes or should I be making a gsp template or something to display and format domain object info? If toString() is just for getting started and should not be used for display purposes long term, then this issue goes away.
public String toString() {
String str = null
if (line1) {
str += line1
}
if (line2) {
if (string.empty == false) {
str += ", "
}
str += line2
}
"${number} ${street} ${extended?:''}, ${city}, ${state}, ${zipcode}".replace(' ,',',')
or
["$number $street",extended,city,state,zipcode].minus(null).join(', ')
Where should you do it is a design decision, is the formatted address gonna be printed in a several different places? If so, you could make a taglib. Generally, I like to keep data formatting responsibilities away from domain classes.