I'm trying to create a simple debug/print function that I can pipe through a sequence of then while processing Future results in Dart.
My function definition is as follows:
import 'dart:async';
typedef FutureOr<T> Pipe<T>(T pipeThrough);
Pipe<A> debug<A>(String log) {
return (A pipeThrough) {
print(log);
return pipeThrough;
};
}
It will return a function that just pipes through whatever it has received from the Future chain, and before that it will print the message log that has been sent to debug.
The way I'm using the function is quite simple:
Future<Map> load(String folder) {
return File(Paths.of([folder, 'data.json']))
.readAsString()
.then((s) => jsonDecode(s))
.then(debug<Map>('JSON LOADED!'));
}
As you can see in the last then in the future chain, it is supposed to return whatever was in the chain, but before that print 'JSON LOADED!'.
But there is something with the generics and Future api that I didn't manage to find a way to make it work, here's the error:
Unhandled exception:
type '(Map<dynamic, dynamic>) => Map<dynamic, dynamic>' is not a subtype of type '(dynamic) => FutureOr<Map<dynamic, dynamic>>'
#0 load (file:///{.../..../......}/data/data_json.dart:11:13)
#1 main (file:///{.../..../......}/data/main.dart:7:28)
#2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
I've tried a bunch of different things, but fundamentally I don't get what's happening, doesn't dart infer the proper types based on the generic types annotation?
I don't know why it can't handle the type here, but changing the code to
Future<Map> load(String folder) {
return File(Paths.of([folder, 'data.json']))
.readAsString()
.then((s) => jsonDecode(s))
.then((v) => debug<Map>('JSON LOADED!')(v));
}
fixes your issue. I had thought that this should be equivalent...
Related
void main() {
print(doStuff.runtimeType);
print(((e) => doStuff(e)).runtimeType);
}
int doStuff(String hallo) {
return 42;
}
executed in the dartpad yields
(String) => int
(dynamic) => int
I would expect both to have the same type. Can somebody explain why dart fails to infer the type of the argument e?
Dart type inference is limited in some ways that inference in purely functional languages is not.
It's not constraint solving based.
So, when the compiler sees (e) => doStuff(e), it checks whether there is a context type from which it can deduce the parameter type.
There isn't (being the receiver of .runtimeType provides no hint). So, it infers dynamic for the parameter, which needs a type before the body of the function can be type analyzed at all.
Then it looks at the body and sees that doStuff(e) is valid and has type int, so that becomes the return type.
I have some code like this:
File("foo.txt").readAsString().catchError((e)=>print(e));
The compiler is complaining
info: The return type 'void' isn't assignable to 'FutureOr<T>', as required by 'Future.catchError'.
I can't seem to give it what it wants and can't find a single clear usage example in any of the docs (just a long issue in git about how many ways there are to mis-use this). If I take the docs at face value, I should be able to return a bool, or a future, neither make the analyzer happy.
How do I provide this FutureOr?
The documentation for Future.catchError could be a lot clearer, but the relevant part is:
onError is called with the error and possibly stack trace, and the returned future is completed with the result of this call in exactly the same way as for then's onError.
Cross-referencing to the documentation for Future.then, the relevant portion is:
The onError callback must return a value or future that can be used to complete the returned future, so it must be something assignable to FutureOr<R>.
Since File.readAsString returns a Future<String>, your catchError callback also must return a Future<String>. Examples of doing that:
File("foo.txt").readAsString().catchError((e) {
print(e);
return Future.value('');
});
File("foo.txt").readAsString().catchError((e) async {
print(e);
return '';
});
Logically, this makes sense; because given:
String value = await File("foo.txt").readAsString().catchError(...);
then if readAsString succeeds, value should be assigned a String. If it fails, since you catch the exception without rethrowing it, value still needs to be assigned a String.
Put another way, your code is equivalent to:
Future<String> readFoo() async {
try {
return await File("foo.txt").readAsString();
} catch (e) {
print(e);
}
// Oops, missing return value.
}
In general, I strongly recommend using async/await with try-catch instead of using .catchError, which would avoid this confusion.
I have nested comments. In order to fetch them from JSON, I have the following fromJson() function:
Comment.fromJson(Map<String, dynamic> json)
: id = json['id'],
...
children = json['children'] != null
? json['children'].map((c) => Comment.fromJson(c)).toList()
: null,
...
This checks if the current comment has any children comments, and if so, recursively parses them from JSON into a Comment. However when I run this, I get the following error:
[ERROR:flutter/shell/common/shell.cc(214)]
Dart Unhandled Exception:
type 'List<dynamic>' is not a subtype of type 'List<Comment>'
stack trace: #0 new Comment.fromJson (package:app/models/comment.dart:43:18)
Which points to the line where I assign children with children = json.... I'm new to dart, but I don't understand how mapping over a list, and returning a Comment doesn't let Dart infer the type of the list. How do I fix this? Adding as List<Comment> after toList() didn't work. If I add as Comment after Comment.fromJson(c), I get unnecessary cast.
Dart can't infer anything from json['children'].map(...).toList() because json['children'] is of type dynamic, and therefore it doesn't know what the .map call is going to resolve to at runtime.
At runtime, since .map is called without an explicit type, it ends up being a call to .map<dynamic>(...), and then .toList() returns List<dynamic>.
Try either:
Explicitly using .map<Comment>(...).
Casting json['children']: (json['children'] as List<Map<String, dynamic>>).map(...). It'd probably be a good idea to validate this anyway.
Working with Futures in Dart, I've come across an interesting issue.
import 'dart:async';
class Egg {
String style;
Egg(this.style);
}
Future cookEggs(List<Egg> list) =>
new Future(() =>
['omelette','over easy'].forEach((_) => list.add(new Egg(_)))
);
Future cookOne(Egg egg) => new Future(() => egg = new Egg('scrambled'));
void main() {
List<Egg> eggList = new List();
Egg single;
cookEggs(eggList).whenComplete(() => eggList.forEach((_) => print(_.style));
cookOne(single).whenComplete(() => print(single.style));
}
The expected output is:
omelette
over easy
scrambled
The cookEggs function that gets the List<Eggs> works fine, but accessing the style property of single is unsuccessful and throws a NoSuchMethodError.
I first thought that this might have something to do with pass-by-reference, but I don't see why Dart would pass a List by reference but not an Egg. Now I'm thinking that the discrepancy may have something to do with the assignment (=) operator and the List.add() method. I'm stuck in that train of thought, and I don't know how to test my hypothesis.
Any thoughts?
The program's output and stack trace is show below:
omelette
over easy
Uncaught Error: The null object does not have a getter 'style'.
NoSuchMethodError: method not found: 'style'
Receiver: null
Arguments: []
Stack Trace:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 main.<anonymous closure> (file:///path/to/eggs.dart:20:51)
#2 _rootRun (dart:async/zone.dart:719)
#3 _RootZone.run (dart:async/zone.dart:862)
#4 _Future._propagateToListeners.handleWhenCompleteCallback (dart:async/future_impl.dart:540)
#5 _Future._propagateToListeners (dart:async/future_impl.dart:577)
#6 _Future._complete (dart:async/future_impl.dart:317)
#7 Future.Future.<anonymous closure> (dart:async/future.dart:118)
#8 _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)
#9 _handleTimeout (dart:io/timer_impl.dart:292)
#10 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:124)
Unhandled exception:
The null object does not have a getter 'style'.
NoSuchMethodError: method not found: 'style'
Receiver: null
Arguments: []
#0 _rootHandleUncaughtError.<anonymous closure>.<anonymous closure> (dart:async/zone.dart:713)
#1 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:23)
#2 _asyncRunCallback (dart:async/schedule_microtask.dart:32)
#3 _asyncRunCallback (dart:async/schedule_microtask.dart:36)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:128)
Quick answer: what gets passed to your functions cookEggs and cookOne are references to the objects, not to the variables (which would be real pass-by-reference).
The term pass-by-reference is often misused to mean pass-references-by-value: many languages only have pass-by-value semantics, where the values that are passed around are references (i.e. pointers, without the dangerous features). See Is Java "pass-by-reference" or "pass-by-value"?
In the case of cookEggs(eggList)…
…the variable eggList contains a reference to a list of eggs. That reference was initially given to you by the expression new List(), and you're passing it to cookEggs after storing meanwhile in your variable eggList. Inside cookEggs, adding to the list works, because you passed a reference to an actual, existing list object.
In the case of cookOne(single)…
…the variable single has only been declared, so it was implicitly initialized by the language runtime to the special reference null. Inside cookOne, you're replacing which reference is contained in egg; since single is a different variable, it still contains null, therefore the code fails when you try to use that.
To clarify
The pass-references-by-value behavior is common to a lot of modern languages (Smalltalk, Java, Ruby, Python…). When you pass an object, you're actually passing-by-value (therefore copying) the contents of your variable, which is a pointer to the object. You never control where objects really exist.
Those pointers are named references rather than pointers, because they are restricted to abstract away the memory layout: you can't know the address of an object, you can't peek at the bytes around an object, you can't even be sure that an object is stored at a fixed place in memory, or that it's stored in memory at all (one could implement object references as UUIDs or keys in a persistent database, as in Gemstone).
In contrast, with pass-by-reference, you'd conceptually pass the variable itself, not its contents. To implement pass-by-reference in a pass-by-value language, you would need to reify variables as ValueHolder objects that can be passed around and whose contents can be changed.
That's because, like Java, Dart is always pass-by-value, and never pass-by-reference. The semantics of passing and assigning in Dart is the same as in Java. Look anywhere on StackOverflow about Java and pass by value to see why Java is described as always pass-by-value. Terms like pass-by-value and pass-by-reference should be used consistently across languages. So Dart should be described as always pass-by-value.
In actual "pass-by-reference", e.g. when a parameter is marked with & in C++ or PHP, or when a parameter is marked with ref or out in C#, simple assignment (i.e. with =) to that parameter variable inside the function will have the same effect as simple assignment (i.e. with =) to the original passed variable outside the function. This is not possible in Dart.
A popular misconception is that Dart is pass-by-reference. However, in a true pass-by-reference system (supported by languages such as C++), a function can set (and not just mutate) local variables in the caller.
Dart, like many other languages (e.g. Java, Python), is technically pass-by-value where the "value" of an object is a reference to it. This is why functions can mutate arguments passed by the caller.
However, in these languages where everything is an object and where there are not separate pointer types, "pass-by-value" and "pass-by-reference" can be confusing terms and are not particularly meaningful. A lot of Python programmers instead use the term pass-by-assignment.
Pass-by-assignment means that arguments are passed in way that's equivalent to normal variable assignment. For example, if I had:
final int x = 42;
final String s = "hello world!";
void foo(int intArgument, String stringArgument) {
...
}
void main() {
foo(x, s);
}
then the behavior would be equivalent to:
final int x = 42;
final String s = "hello world!";
void foo() {
int intArgument = x;
String stringArgument = s;
...
}
void main() {
foo();
}
When you do String stringArgument = s;, stringArgument and s are two separate variables referring to the same object. Reassigning stringArgument to something else won't change what s refers to. However, if you mutate that object in place, both stringArgument and s will refer to the now modified object.
I don´t understand the syntax of the then() clause.
1. myFuture(6).then( (erg) => print(erg) )
What´s (erg) => expr syntactically?
I thougt it could be a function, but
then( callHandler2(erg)
doesn´t work, Error:
"Multiple markers at this line
- The argument type 'void' cannot be assigned to the parameter type '(String) ->
dynamic'
- Undefined name 'erg'
- Expected to find ')'"
2. myFuture(5).then( (erg) { callHandler(erg);},
onError: (e) => print (e)
What´s `onError: (e) => expr"` syntactically?
3. Is there a difference between the onError: and the .catchError(e) variants?
1) The Fat Arrow is syntactic sugar for short anonymous functions. The two functions below are the same:
someFuture(arg).then((erg) => print(erg));
// is the same as
someFuture(arg).then((erg) { return print(erg); });
Basically the fat arrow basically automatically returns the evaluation of the next expression.
If your callHandler2 has the correct signature, you can just pass the function name. The signature being that it accept the number of parameters as the future will pass to the then clause, and returns null/void.
For instance the following will work:
void callHandler2(someArg) { ... }
// .. elsewhere in the code
someFuture(arg).then(callHandler);
2) See answer 1). The fat arrow is just syntactic sugar equivalent to:
myFuture(5).then( (erg){ callHandler(erg);}, onError: (e){ print(e); });
3) catchError allows you to chain the error handling after a series of futures. First its important to understand that then calls can be chained, so a then call which returns a Future can be chained to another then call. The catchError will catch errors both synchronous and asynchronous from all Futures in the chain. Passing an onError argument will only deal with an error in the Future its an argument for and for any synchronous code in your then block. Any asynchronous code in your then block will remain uncaught.
Recent tendency in most Dart code is to use catchError and omit the onError argument.
I will attempt to elaborate more on Matt's answer, hopefully to give more insights.
What then() requires is a function (callback), whose signature matches the future's type.
For example, given a Future<String> myFuture and doSomething being any function that accepts a String input, you can call myFuture.then(doSomething). Now, there are several ways to define a function that takes a String in Dart:
Function(String) doSomething1 = (str) => /* do something with str */ // only one command
Function(String) doSomething2 = (str) { /* do something with str */ } // several commands
Function(String) doSomething3 = myFunction;
myFunction(String) { // Dart will auto imply return type here
/* do something with str */ // several commands
}
Any of those 3 function definitions (the right hand side of =) could go inside then(). The first two definitions are called lambda functions, they are created at runtime and cannot be reused unless you manually copy the code. Lambda functions can potentially yield language-like expressions, i.e. (connection) => connection.connect(). The third approach allows the function to be reused. Lambda functions are common in many languages, you can read more about it here: https://medium.com/#chineketobenna/lambda-expressions-vs-anonymous-functions-in-javascript-3aa760c958ae.
The reason why you can't put callHandler2(erg) inside then() is because callHandler2(erg) uses an undefined variable erg. Using the lambda function, you will be able to tell then() that the erg in callHandler2(erg) is the output of the future, so it knows where to get erg value.