How come in dart in a line of code such as this one:
MaterialPageRouter(builder: (context) => MyWidget())
We are returning MyWidget class with out instantiating it with the keyword new as in new MyWidget() ? Are we just returning the class itself and something happens under the hood that uses the new keyword to do whats required. Or something else is happening?
new became optional in Dart 2. You can just omit it or write it. It doesn't make a difference.
MyWidget() creates a new instances and this is what is returned.
Related
I've recently upgraded Dart (using v2.12.4) and trying to migrate an app I've made.
I'm now stuck at an issue that I can't seem to resolve.
Consider the following pseudo-code:
class Notifications {
Future<List<NotificationItem>> notificationItems;
fillNotificationList() async {
notificationItems = await httpService.getFromEndpoint();
}
}
The notificationItems currently errors with Non-nullable instance field 'notifications' must be initialized..
I've tried different solutions; adding late keyword makes the application throw a LateInitializationError exception and appending = [] gives a type error.
How can I successfully have a Future variable with the null safety features in recent versions of Dart?
It seems to be a nullable variable. Meaning there is a point in time in your program where this is clearly null. So declare it as such:
Future<List<NotificationItem>>? notificationItems;
The rest of your code seems a little weird to me. You named a future like I would name the actual result. You have an async method that doesn't do any async work. Maybe that's just because the example here is simplified.
Or maybe you really really want to insist this is never null. You could initialize it with a completed Future with an empty list:
Future<List<NotificationItem>>? notificationItems = Future.value(<NotificationItem>[]);
beginner in Flutter here,
Does anybody know the difference, or significance of the keyword get in the context of instantiating a widget?
I'm declaring a widget here
ListTile sampleListTile {
return ListTile(...);
}
In this scenario, I'm getting an error of Methods must have an explicit list of parameters., to be solved by coding it as a method by adding () to the widgetname.
But here,
ListTile get sampleListTile {
return ListTile(...);
}
Everything works out alright... I tried searching around but I can't nail down the relevant article.
Please help. thanks.
Your first syntax is an "instance method", so the syntax should be (note the extra ()):
ListTile sampleListTile() {
return ListTile(...);
}
which you call like:
ListTile foo = sampleListTile();
and can have parameters as necessary.
The second syntax is of a getter which are special instance methods that have no parameters. They feel more like "instance variables" in that you use them like:
ListTile bar = sampleListTile;
I came across the following code example from flutter_redux example code. Had a hard time to understand why factory SearchState.initial() returns with a new keyword while factory SearchState.loading() and factory SearchState.error() don't.
class SearchState {
final SearchResult result;
final bool hasError;
final bool isLoading;
SearchState({
this.result,
this.hasError = false,
this.isLoading = false,
});
factory SearchState.initial() =>
new SearchState(result: SearchResult.noTerm());
factory SearchState.loading() => SearchState(isLoading: true);
factory SearchState.error() => SearchState(hasError: true);
}
Just found the Dart language tour not very helpful to this case, and the Dart language specification is too obscure.
Quotes from the effective dart guide:
Dart 2 makes the new keyword optional. Even in Dart 1, its meaning was
never clear because factory constructors mean a new invocation may
still not actually return a new object.
The language still permits new in order to make migration less
painful, but consider it deprecated and remove it from your code.
There is no difference. In Dart 2, the new keyword was made optional. If you don't write anything when calling a constructor, it's implicitly assumed to be new.
Most code still uses new because it was required in Dart 1, and some people even prefer it, so you will see code both with and without new.
In my Dart based application I just noticed that I can omit the new keyword and everything works perfectly fine.
Instead of final widget = new Widget(); I can also use final widget = Widget();.
Does this have any effect in code?
No, it does not. With Dart 2 (click for the announcement with more information) the new and also const keywords were made optional.
This means that new Widget() does the exact same as Widget() on its own.
The const keyword can, however, change a value that would not be a const implicitly to a const.
So you will have to explicitly specify const when needed.
In Dart 2, if you invoke a constructor like a function, without a new or const in front, then it is equivalent to using new.
If you want a const invocation, then you should put const in front.
Inside a const expression, you don't need to write const again, and in some contexts that require const expressions (like switch case expressions and initializers of const variables), you don't even need the outer const.
So you don't ever need to write new.
Dart language team wants to allow expressions where you can insert either new or const and still have the invocation be correct (that is, a const constructor with constant arguments) to default to inserting const instead of new, hopefully in an early update to Dart 2.
For that reason, I recommend writing new it in front of Object(), or any other const constructor where you need the object to be a new instance. That's a very rare case, usually you don't care about the identity of your immutable object (which is why inserting const is considered a good idea). (That plan didn't pan out, so you can ignore this.)
The new keyword was made optional in Dart 2. As of now, calling a class will always return a new instance of that class. As per my recommendation, you can use it (NOT MANDATORY) outside of a Layout definition, but omit in inside Layouts.
One more point which I would like to share with you guys is that if you use new or const keyword while declaring widgets, you are also able to see the + icon which you can use to collapse and expand the widget body code. This is useful when you want to collapse/hide the rest widget code in dart file while working on another widget code in the same file.
I was wondering if anyone had an idea for the best way to provide the
functionality of bindData() outside of my grails controllers. In my current
project I have created several groovy classes to model objects returned by
an api. In these classes I have a static method that parses xml and returns
a List of objects of the class. I would like to skip all the type casting
nonsense by using the bindData method in these classes. Any suggestions on
how to do this would be appreciated.
I was looking for a similar solution, to use bindData in a service class. I found a solution in JT's blog. The solution is basically to import:
import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod
then add this to your code:
def foo = new Foo()
BindDynamicMethod bind = new BindDynamicMethod()
def args = [ foo, params, [exclude:['name', 'mail']] ] // for example
bind.invoke( foo, 'bind', (Object[])args)
The (Object[]) cast is necessary du to Groovy/Java compatability. (Groovy is treating the ‘args’ object as an ArrayList, not an array of Objects.)