Language Basics
Before creating our first Flutter app, let's see how Dart syntax works.
tip
We'll only scratch the surface of the Dart's syntax here that's necessary to complete today's tasks. If you want to learn more, head to official language tour.
Variable definition
Variables store references. The variable called hello
contains a reference to a String
object with a value of “Hello, World!”.
note
The type of the name variable is inferred to be String, but you can change that type by specifying it.
To specify that hello should be a String
instance, use:
You can also allow to store more than one type of objects in hello
variable by declaring it as a dynamic
:
Final and const
If you never intend to change a variable, use final or const, either instead of var or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant.
note
Const variables are implicitly final.
A final top-level or class variable is initialized the first time it’s used.
Use const for variables that you want to be compile-time constants. Where you declare the variable, set the value to a compile-time constant such as a number or string literal, a const variable, or the result of an arithmetic operation on constant numbers:
Classes
Class syntax:
Enums
Enum example:
copyWith()
pattern
There's a common pattern visible in a lot of Flutter data structures called copyWith()
. Implementation looks like this:
copyWith()
pattern uses named parameters and conditional operator ??
. It allows easy modification of an instance values without loosing previous ones. It really handy when you want to edit just one of many fields of an object.
Example usage:
tip
The copyWith()
pattern is used in a lot of Flutter components, eg. TextStyle. Let's imagine that you want to change just the text color, leaving font family, size, line height and other properties unchanged. copyWith()
pattern allows you to do as a oneliner
instead of redefining the whole object, like so