So Im learning Dart right now, and I have a problem when it comes to declare lists. In a tutorial I saw that the teacher declared a list by using this syntax:
void main() {
final names = ['Foo', 'Bar', 'Baz'];
}
And in another turorial I saw this:
void main() {
List<String> names = ['Foo', 'Bar', 'Baz'];
}
I want to know if there is a differance between the two.
And thank you guys for reading my question
CodePudding user response:
final
just means that once assigned it can't be reassigned. So you can't do
final names = ['Foo', 'Bar', 'Baz'];
names = ['Foo2', 'Bar2', 'Baz2'];
You could add it also to the other one as well like
final List<String> names = ['Foo', 'Bar', 'Baz'];
Without final it's fine to do
List<String> names = ['Foo', 'Bar', 'Baz'];
names = ['Foo2', 'Bar2', 'Baz2'];
Furthermore it's usually okay to leave out the type, because the compiler is smart enough to see that it is in fact a List<String>
in this case. If you want to make a non-final variable without indicating the type you can use the keyword var
, like
var names = ['Foo', 'Bar', 'Baz'];
So in these examples
var names = ['Foo', 'Bar', 'Baz'];
List<String> names = ['Foo', 'Bar', 'Baz'];
are identical, and
final names = ['Foo', 'Bar', 'Baz'];
final List<String> names = ['Foo', 'Bar', 'Baz'];
are identical.
CodePudding user response:
First one is the List which can be use as dynamic list or you can use as
List<dynamic> name= ['one,'two','three'];
Where as second one is used for specific String List OR
List<int> numbers= [1,2,3];