now, we will start learning Dart. Dart is the foundation of Flutter, and if you want to develop apps using Flutter, you must learn Dart.
Currently, Flutter can be regarded as the best cross-platform development method.
Here, I recommend using the website DartPad directly to run Dart code. The URL is dartpad.dev, and for users in China, you can use dartpad.cn.
the most fundamental and core part of Dart programming — variables and data types. If we compare a program to a building, variables are like the bricks, and data types are the material specifications of those bricks. Mastering the content of this section will lay a solid foundation for our subsequent Dart learning.
I. Variable Declaration: Giving a “Name” to Data
In Dart, variables are like labeled boxes used to store various types of data. There are three ways to declare variables, each suitable for different scenarios. Let’s take a look at them one by one.
1.Explicit Type Declaration (Recommended)
Specifying the variable type directly makes the code more readable and is the standard practice in enterprise development.
void main() {
String username = "Flutter"; // Explicitly declared as a string
int score = 95; // Explicitly declared as an integer
bool isPass = true; // Explicitly declared as a boolean
// Type mismatch will directly result in a compilation error
// String height = 175; // Error: Cannot assign int to String
}
2.Declaring Dynamically Typed Variables with dynamic
Variables declared with dynamic can change types at any time. Dart does not perform type checks, offering high flexibility but low security.
void main() {
dynamic value = "Hello";
print(value.length); // Correct: It is a String type at this point, which has a length property
value = 100; // Can be changed to int type
// print(value.length); // Runtime error: int type has no length property
}
3. Declaring Variables with var (Type Inference)
var is the most concise way to declare variables. Dart automatically infers the variable type based on the initial value, and once the type is determined, it cannot be changed.
void main() {
// Declare and initialize variables
var age = 25; // Dart infers int type
var name = "Dart"; // Infers String type
var isStudent = true; // Infers bool type
// Attempting to change to another type will result in an error
// age = "25"; // Error: int type variable cannot be assigned a string
}
II. Basic Data Types in Dart
Dart has four most commonly used basic data types, each corresponding to different data forms. Let’s get to know them one by one.
1. Integer Type (int)
Used to store numbers without a fractional part, ranging from - 2 ⁶³to 2 ⁶³-1.
void main() {
int a = 10;
int b = -5;
int c = 0x1A; // Hexadecimal (starts with 0x), equivalent to 26
print(a + b); // Outputs 5
print(c * 2); // Outputs 52
}
Common Operations: + (addition), — (subtraction), * (multiplication), / (division, returns double), ~/ (integer division, returns int), % (modulus).
2. Floating-Point Type (double)
Used to store numbers with a fractional part, following the 64-bit double-precision IEEE 754 standard.
void main() {
double pi = 3.14159;
double gravity = 9.8;
double scientific = 2.5e3; // Scientific notation, equivalent to 2500.0
print(pi * 2); // Outputs 6.28318
print(gravity / 2); // Outputs 4.9
}
Note: Both int and double belong to the num type. Variables of the num type can receive both integers and floating-point numbers.
num x = 10; // Correct
x = 3.14; // Also correct
3. String Type (String)
Used to store text data, enclosed in single quotes (‘) or double quotes (“), and supports multi-line strings (triple quotes).
void main() {
String single = 'Single-quoted string';
String double = "Double-quoted string";
String multi = """
Multi-line string
Can wrap lines
Preserves formatting
""";
print(single);
print(double);
print(multi);
}
Three Ways to Concatenate Strings:
Using the + sign
Referencing variables with $ (for single variables)
Executing expressions with ${} (for complex calculations)
void main() {
String firstName = "Zhang";
String lastName = "San";
int age = 20;
// Method 1: Concatenation with +
String fullName1 = firstName + lastName; // "Zhang San"
// Method 2: Referencing variables with $
String info1 = "Name:$fullName1"; // "Name: ZhangSan"
// Method 3: Executing expressions with ${}
String info2 = "Age next year:${age + 1}"; // "Age next year: 21"
}
4. Boolean Type (bool)
Has only two values: true and false, used for logical judgments.
void main() {
bool isReady = true;
bool hasError = false;
int score = 85;
bool isPass = score >= 60; // true
print(isReady && hasError); // false (logical AND)
print(isReady || hasError); // true (logical OR)
print(!isReady); // false (logical NOT)
}
Note: Dart is a strongly typed language. You cannot use 0 or non-null values to replace false/true, which is different from JavaScript.
// Error example
bool flag = 0; // Compilation error: Cannot assign int to bool
III. Type Conversion: The “Shape-Shifting” of Data Types
In actual development, we often need to convert data between different types, such as converting a user-input string to a number for calculation. Dart provides convenient conversion methods, but we need to be careful about handling conversion failures.
1. Converting Between Strings and Numbers
String to Number
int.parse(): Converts a string to int (only for integer formats)
double.parse(): Converts a string to double (for integer or decimal formats)
void main() {
String numStr1 = "123";
int num1 = int.parse(numStr1); // 123
String numStr2 = "3.14";
double num2 = double.parse(numStr2); // 3.14
// Conversion failure will throw a FormatException
try {
int error = int.parse("abc");
} catch (e) {
print("Conversion failed:$e"); // Outputs error message
}
}
Number to String
Using the toString() method
Converting an integer to a string with a specified number of decimal places: toStringAsFixed(n)
void main() {
int a = 100;
String str1 = a.toString(); // "100"
double b = 3.1415;
String str2 = b.toString(); // "3.1415"
String str3 = b.toStringAsFixed(2); // "3.14"(save 2 decimal places)
}
2. Other Common Conversions
bool to string: true.toString() → “true”
Number to bool: 0 and 0.0 are not automatically converted to false in judgments (explicit comparison is required)
void main() {
int x = 0;
if (x == 0) {
// Explicit judgment is necessary
print("x is 0");
}
}
IV. Practical Exercise: Temperature Converter
Let’s do a small exercise to consolidate today’s knowledge: Write a program to convert Celsius to Fahrenheit. The formula is: Fahrenheit = Celsius × 1.8 + 32.
void main() {
// 1. Declare and initialize the Celsius variable
double celsius = 25.5;
// 2. Calculate Fahrenheit
double fahrenheit = celsius * 1.8 + 32;
// 3. Output the result (save 1 decimal place)
print("Celsius:$celsius ℃");
print("Fahrenheit:${fahrenheit.toStringAsFixed(1)} ℉");
}
Running result:
Celsius:25.5 ℃
Fahrenheit:77.9 ℉
You can try modifying the value of celsius to see if the conversion result is correct. You can also try implementing the conversion of integer temperatures using the int type.
Top comments (0)