In TypeScript, I can simply define an anonymous object like below and still get intellisense for it.
let person = {
age: 10,
}
Unfortunately, I cannot able to do that same in the dart lang.
But I can do something similar using class and static properties.
class Person {
static age = 10;
}
This gets the job done but I wonder if there are any simpler approach for this.
Dart 3 introduces Record
s, which allow you do what you want:
final person = (
name: 'Foo',
username: '@bar',
age: 45,
greet: () => 'Hello, Foo',
greetIAm: (String iam) => 'Hello, Foo! I am $iam',
);
void main() {
// Foo
print(person.name);
// @bar
print(person.username);
// 45
print(person.age);
// Hello Foo!
print(person.greet());
// Hello Foo! I am Bar!
print(person.greetIAm('Bar!'));
}
You can also define types that declare the fields you want without the need to declare a new class:
typedef Person = ({
String name,
int age,
});
// With positional values instead:
typedef PersonButWithUnnamedParams = (
String name,
int age,
);
Person createPerson(String name, int age) {
return (
name: name,
age: age,
);
}
// Create a var direct from the type definitio.
final Person stranger = (
age: -1,
name: 'Stranger',
);
// Create a var of type Person through a function.
final Person stranger2 = createPerson('Stranger', -1);
// Positional params are also supported.
final PersonButWithUnnamedParams stranger3 = (
'Stranger',
-1,
);
Limitations:
You can't.
Dart doesn't support anonymous types.
You can define a Map
:
final person = <String, int>{'age': 10};
But in the intellisense perspective it is only a Map
which contains keys of type String
and values of type int
, can't infer that there's a key age
of value 10
So you should define it as a class if you want intellisense:
class Person {
const Person(this.age);
final int age;
}
const person = Person(10);
print(person.age); // 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With