Appearance
Dart语言基础
Dart是Google开发的面向对象的编程语言,专为客户端优化,是Flutter框架的开发语言。本章将介绍Dart语言的核心特性和基础语法。
Dart语言概述
Dart特性
Dart是一种现代、面向对象的语言,具有以下特性:
- 强类型系统(可选类型)
- 面向对象编程
- 函数是一等公民
- 支持异步编程
- 垃圾回收机制
- 单线程事件循环
dart
// 简单的Dart程序示例
void main() {
print('Hello, Dart!');
// 变量声明
String name = 'Flutter Developer';
int age = 25;
double score = 95.5;
bool isActive = true;
print('Name: $name, Age: $age, Score: $score, Active: $isActive');
}
变量和数据类型
变量声明
dart
void variableExample() {
// var - 类型由编译器推断
var userName = 'John Doe';
var userAge = 30;
// final - 运行时初始化的常量
final String email = 'john@example.com';
final List<String> hobbies = ['reading', 'swimming'];
// const - 编译时常量
const String appName = 'MyApp';
const List<String> platforms = ['Android', 'iOS', 'Web', 'Desktop'];
// dynamic - 动态类型
dynamic value = 'This is a string';
value = 42; // 可以更改为其他类型
print('User: $userName, Email: $email');
}
数据类型
dart
void dataTypeExample() {
// 数值类型
int integerNum = 42;
double doubleNum = 3.14159;
num mixedNum = 10; // 可以是int或double
// 字符串类型
String singleLine = 'This is a single line string.';
String multiLine = '''
This is a
multi-line string.
''';
String interpolation = 'The answer is ${integerNum + doubleNum}';
// 布尔类型
bool isTrue = true;
bool isFalse = false;
// 列表(数组)
List<String> fruits = ['apple', 'banana', 'orange'];
List<int> numbers = [1, 2, 3, 4, 5];
var dynamicList = [1, 'hello', true]; // 混合类型列表
// 集合(Set)
Set<String> uniqueItems = {'red', 'green', 'blue'};
// 映射(Map)
Map<String, dynamic> person = {
'name': 'John',
'age': 30,
'isMarried': false,
};
print('Interpolated: $interpolation');
print('Fruits: $fruits');
print('Person: $person');
}
函数
函数声明
dart
// 基本函数
String greet(String name) {
return 'Hello, $name!';
}
// 箭头函数(单表达式)
int square(int x) => x * x;
// 可选参数
String buildFullName(String firstName, String lastName, [String? middleName]) {
if (middleName != null) {
return '$firstName $middleName $lastName';
}
return '$firstName $lastName';
}
// 命名参数
void configureApp({String? theme, bool? darkMode, int? fontSize}) {
print('Theme: $theme, Dark Mode: $darkMode, Font Size: $fontSize');
}
// 默认参数值
String formatCurrency(double amount, {String currency = 'USD'}) {
return '${currency}\$${amount.toStringAsFixed(2)}';
}
// 函数作为参数
void executeWithCallback(Function callback) {
print('Before callback');
callback();
print('After callback');
}
void functionExample() {
print(greet('Alice'));
print(square(5));
print(buildFullName('John', 'Doe', 'Middle'));
print(formatCurrency(123.45));
configureApp(theme: 'Material', darkMode: true);
executeWithCallback(() {
print('This is the callback function');
});
}
匿名函数和闭包
dart
void anonymousFunctionExample() {
// 匿名函数
var multiply = (int a, int b) {
return a * b;
};
print('Multiply: ${multiply(5, 3)}');
// 闭包
int multiplier = 10;
Function createMultiplier(int factor) {
return () {
return multiplier * factor;
};
}
var doubleMultiplier = createMultiplier(2);
print('Double multiplier result: ${doubleMultiplier()}');
// Lambda表达式
List<int> numbers = [1, 2, 3, 4, 5];
List<int> doubled = numbers.map((n) => n * 2).toList();
print('Original: $numbers, Doubled: $doubled');
}
控制流
条件语句
dart
void controlFlowExample() {
int score = 85;
// if-else语句
if (score >= 90) {
print('Grade: A');
} else if (score >= 80) {
print('Grade: B');
} else if (score >= 70) {
print('Grade: C');
} else {
print('Grade: F');
}
// switch语句
String day = 'Monday';
switch (day) {
case 'Saturday':
case 'Sunday':
print('Weekend');
break;
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
print('Weekday');
break;
default:
print('Unknown day');
}
// 三元运算符
String status = score >= 60 ? 'Passed' : 'Failed';
print('Status: $status');
// 逻辑运算符
bool isAdult = true;
bool hasLicense = true;
bool canDrive = isAdult && hasLicense;
print('Can drive: $canDrive');
}
循环语句
dart
void loopExample() {
// for循环
for (int i = 0; i < 5; i++) {
print('For loop: $i');
}
// for-in循环
List<String> items = ['apple', 'banana', 'orange'];
for (String item in items) {
print('Item: $item');
}
// while循环
int counter = 0;
while (counter < 3) {
print('While loop: $counter');
counter++;
}
// do-while循环
int doCounter = 0;
do {
print('Do-while loop: $doCounter');
doCounter++;
} while (doCounter < 2);
// break和continue
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // 跳过3
if (i == 7) break; // 在7处停止
print('Loop with control: $i');
}
}
面向对象编程
类和对象
dart
// 基本类定义
class Person {
String name;
int age;
String email;
// 构造函数
Person(this.name, this.age, this.email);
// 命名构造函数
Person.adult(String name, String email) : this(name, 18, email);
// 工厂构造函数
factory Person.fromMap(Map<String, dynamic> map) {
return Person(
map['name'] ?? '',
map['age'] ?? 0,
map['email'] ?? '',
);
}
// 方法
void introduce() {
print('Hi, I am $name, $age years old.');
}
// getter和setter
String get displayName => 'Mr./Ms. $name';
set setName(String newName) {
if (newName.length > 2) {
name = newName;
}
}
}
// 继承
class Student extends Person {
String school;
double gpa;
Student(String name, int age, String email, this.school, this.gpa)
: super(name, age, email);
@override
void introduce() {
super.introduce();
print('I study at $school with GPA: $gpa');
}
void study() {
print('$name is studying hard.');
}
}
// 抽象类
abstract class Animal {
String name;
Animal(this.name);
// 抽象方法
void makeSound();
// 具体方法
void eat() {
print('$name is eating.');
}
}
// 实现接口
class Dog extends Animal {
Dog(String name) : super(name);
@override
void makeSound() {
print('$name says Woof!');
}
}
void oopExample() {
// 创建对象
Person person = Person('John Doe', 25, 'john@example.com');
person.introduce();
print('Display name: ${person.displayName}');
Student student = Student('Jane Smith', 20, 'jane@example.com', 'MIT', 3.8);
student.introduce();
student.study();
Dog dog = Dog('Buddy');
dog.eat();
dog.makeSound();
}
Mixin
dart
// Mixin定义
mixin Flyable {
void fly() {
print('Flying...');
}
void land() {
print('Landing...');
}
}
mixin Swimmable {
void swim() {
print('Swimming...');
}
}
// 使用Mixin
class Duck extends Animal with Flyable, Swimmable {
Duck(String name) : super(name);
@override
void makeSound() {
print('$name says Quack!');
}
}
void mixinExample() {
Duck duck = Duck('Donald');
duck.makeSound();
duck.fly();
duck.swim();
duck.land();
}
异步编程
Future和异步函数
dart
// 异步函数
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data fetched successfully!';
}
Future<void> asyncExample() async {
print('Start fetching data...');
try {
String result = await fetchData();
print(result);
} catch (e) {
print('Error: $e');
}
}
// Future的链式调用
void futureChainExample() {
Future<String> getData() {
return Future.delayed(Duration(seconds: 1), () => 'Hello');
}
getData()
.then((value) => '$value World!')
.then((value) => print(value))
.catchError((error) => print('Error: $error'));
}
// 并发执行多个Future
Future<void> concurrentExample() async {
Future<String> fetchUserOrder() {
return Future.delayed(Duration(seconds: 2), () => 'Large Latte');
}
Future<String> fetchUserInfo() {
return Future.delayed(Duration(seconds: 1), () => 'John Doe');
}
// 同时执行
var results = await Future.wait([
fetchUserOrder(),
fetchUserInfo(),
]);
print('Order: ${results[0]}, User: ${results[1]}');
}
Stream
dart
Stream<int> countStream() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(milliseconds: 500));
yield i;
}
}
void streamExample() {
countStream().listen(
(value) => print('Stream value: $value'),
onDone: () => print('Stream completed'),
onError: (error) => print('Stream error: $error'),
);
}
泛型
dart
// 泛型类
class Container<T> {
T? value;
Container(this.value);
T? getValue() => value;
void setValue(T newValue) {
value = newValue;
}
}
// 泛型方法
T getFirstElement<T>(List<T> list) {
if (list.isEmpty) throw ArgumentError('List is empty');
return list.first;
}
// 泛型约束
class NumberProcessor<T extends num> {
T value;
NumberProcessor(this.value);
T multiplyByTwo() {
return (value * 2) as T;
}
}
void genericExample() {
// 使用泛型类
Container<String> stringContainer = Container('Hello');
Container<int> intContainer = Container(42);
print('String: ${stringContainer.getValue()}');
print('Int: ${intContainer.getValue()}');
// 使用泛型方法
List<String> names = ['Alice', 'Bob', 'Charlie'];
String first = getFirstElement(names);
print('First name: $first');
// 使用泛型约束
NumberProcessor<int> processor = NumberProcessor(10);
print('Multiplied: ${processor.multiplyByTwo()}');
}
异常处理
dart
void exceptionExample() {
try {
int result = 10 ~/ 0; // 会产生异常
} on IntegerDivisionByZeroException {
print('Cannot divide by zero!');
} catch (e) {
print('An error occurred: $e');
} finally {
print('This will always execute');
}
// 抛出异常
try {
validateAge(-5);
} catch (e) {
print('Caught exception: $e');
}
}
void validateAge(int age) {
if (age < 0) {
throw ArgumentError('Age cannot be negative');
}
}
扩展方法
dart
// 扩展方法
extension StringExtension on String {
bool get isValidEmail {
return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(this);
}
String get capitalize {
if (isEmpty) return this;
return this[0].toUpperCase() + substring(1).toLowerCase();
}
int get wordCount {
return split(RegExp(r'\s+')).length;
}
}
void extensionExample() {
String email = 'test@example.com';
print('Is valid email: ${email.isValidEmail}');
String name = 'john doe';
print('Capitalized: ${name.capitalize}');
String sentence = 'This is a sample sentence';
print('Word count: ${sentence.wordCount}');
}
注解
dart
// 常用注解
class ApiResponse {
@deprecated
String oldField = '';
@override
String toString() => 'ApiResponse';
@required // 需要导入foundation
String requiredField = '';
}
// 自定义注解
class Configurable {
final String name;
final String description;
const Configurable(this.name, this.description);
}
class AppConfig {
@Configurable('theme', 'Application theme setting')
String theme = 'light';
@Configurable('language', 'Application language')
String language = 'en';
}
Dart与Flutter集成
在Flutter中使用Dart特性
dart
import 'package:flutter/material.dart';
class DartFeaturesDemo extends StatefulWidget {
@override
_DartFeaturesDemoState createState() => _DartFeaturesDemoState();
}
class _DartFeaturesDemoState extends State<DartFeaturesDemo> {
List<Map<String, dynamic>> _users = [];
bool _isLoading = false;
@override
void initState() {
super.initState();
_loadUsers();
}
// 异步加载数据
Future<void> _loadUsers() async {
setState(() {
_isLoading = true;
});
try {
// 模拟网络请求
await Future.delayed(Duration(seconds: 2));
// 使用Dart的列表和映射特性
_users = [
{'id': 1, 'name': 'Alice Johnson', 'email': 'alice@example.com'},
{'id': 2, 'name': 'Bob Smith', 'email': 'bob@example.com'},
{'id': 3, 'name': 'Carol Davis', 'email': 'carol@example.com'},
];
} catch (e) {
print('Error loading users: $e');
} finally {
setState(() {
_isLoading = false;
});
}
}
// 使用扩展方法格式化数据
String _formatUserName(String name) {
return name.split(' ').map((word) =>
word[0].toUpperCase() + word.substring(1).toLowerCase()
).join(' ');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dart Features in Flutter'),
),
body: _isLoading
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
final user = _users[index];
return Card(
margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: ListTile(
leading: CircleAvatar(
child: Text(user['name'][0]),
),
title: Text(_formatUserName(user['name'])),
subtitle: Text(user['email']),
trailing: Icon(Icons.arrow_forward_ios),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _loadUsers,
child: Icon(Icons.refresh),
),
);
}
}
最佳实践
代码风格和规范
dart
// 1. 使用final声明不可变变量
class UserProfile {
final String id;
final String name;
final String email;
final DateTime createdAt;
// 2. 使用命名构造函数提高可读性
UserProfile({
required this.id,
required this.name,
required this.email,
DateTime? createdAt,
}) : createdAt = createdAt ?? DateTime.now();
// 3. 使用工厂构造函数处理复杂初始化
factory UserProfile.fromJson(Map<String, dynamic> json) {
return UserProfile(
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
createdAt: DateTime.parse(json['created_at'] as String),
);
}
// 4. 使用getter进行计算属性
String get displayName => name.split(' ')[0];
bool get isEmailValid {
return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
}
// 5. 实现toString方法便于调试
@override
String toString() {
return 'UserProfile(id: $id, name: $name, email: $email)';
}
}
Dart语言是Flutter开发的基础,掌握其核心概念和特性对于成为优秀的Flutter开发者至关重要。通过理解变量、函数、面向对象编程、异步编程等概念,可以更好地构建高质量的Flutter应用。