Appearance
Flutter基础概念
Flutter是Google开发的开源UI工具包,可以帮助开发者使用一套代码库为移动、Web和桌面构建高性能、高保真的应用程序。本文档将介绍Flutter的核心概念和基础知识。
Flutter架构概览
三层架构
Flutter采用三层架构设计:
- Framework层:Dart编写的高级抽象层
- Engine层:C++编写的渲染引擎
- Embedder层:适配不同操作系统的嵌入器
dart
// Flutter应用的基本结构示例
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
核心概念
Widget(部件)
Widget是Flutter UI的基本构建块,一切皆为Widget。Widget描述了UI的一部分应该如何配置。
dart
// StatelessWidget示例 - 不可变的部件
class GreetingWidget extends StatelessWidget {
final String name;
GreetingWidget({required this.name});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16.0),
child: Text(
'Hello, $name!',
style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
),
);
}
}
// StatefulWidget示例 - 可变的部件
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: () {
setState(() {
_count++;
});
},
child: Text('Increment'),
),
],
);
}
}
Element(元素)
Element是Widget的实例,代表Widget在UI树中的位置。每个Widget在构建时都会创建对应的Element。
RenderObject(渲染对象)
RenderObject负责布局、绘制和处理手势,是实际渲染到屏幕的对象。
Widget类型
StatelessWidget
不包含状态变化的Widget,其属性不可更改。
dart
class WelcomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.blue, Colors.purple],
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.star,
size: 100,
color: Colors.white,
),
SizedBox(height: 20),
Text(
'Welcome to Flutter',
style: TextStyle(
fontSize: 24,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
);
}
}
StatefulWidget
包含可变状态的Widget,当状态改变时会重新构建。
dart
class TodoList extends StatefulWidget {
@override
_TodoListState createState() => _TodoListState();
}
class _TodoListState extends State<TodoList> {
List<String> _todos = [];
final TextEditingController _controller = TextEditingController();
void _addTodo() {
if (_controller.text.isNotEmpty) {
setState(() {
_todos.add(_controller.text);
_controller.clear();
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Todo List')),
body: ListView.builder(
itemCount: _todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_todos[index]),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
_todos.removeAt(index);
});
},
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _addTodo,
child: Icon(Icons.add),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
布局基础
容器类Widget
dart
class LayoutExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Container - 提供装饰、填充、边距等功能
Container(
height: 100,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8.0),
),
child: Center(
child: Text(
'Container Example',
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(height: 16),
// Padding - 添加内边距
Padding(
padding: EdgeInsets.all(8.0),
child: Container(
color: Colors.green,
child: Text('Padded Content'),
),
),
SizedBox(height: 16),
// Center - 居中内容
Center(
child: Container(
width: 200,
height: 50,
color: Colors.red,
child: Center(child: Text('Centered')),
),
),
],
),
),
);
}
}
布局类Widget
dart
class LayoutWidgets extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// Row - 水平布局
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 80,
height: 80,
color: Colors.red,
child: Center(child: Text('1')),
),
Container(
width: 80,
height: 80,
color: Colors.green,
child: Center(child: Text('2')),
),
Container(
width: 80,
height: 80,
color: Colors.blue,
child: Center(child: Text('3')),
),
],
),
SizedBox(height: 16),
// Column - 垂直布局
Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 200,
height: 50,
color: Colors.orange,
child: Center(child: Text('Row 1')),
),
SizedBox(height: 8),
Container(
width: 200,
height: 50,
color: Colors.pink,
child: Center(child: Text('Row 2')),
),
],
),
SizedBox(height: 16),
// Expanded - 填充可用空间
Row(
children: [
Container(
width: 50,
height: 50,
color: Colors.grey,
child: Center(child: Text('Fixed')),
),
Expanded(
child: Container(
height: 50,
color: Colors.yellow,
child: Center(child: Text('Expanded')),
),
),
Container(
width: 50,
height: 50,
color: Colors.grey,
child: Center(child: Text('Fixed')),
),
],
),
],
),
);
}
}
应用生命周期
dart
class LifecycleAwareApp extends StatefulWidget {
@override
_LifecycleAwareAppState createState() => _LifecycleAwareAppState();
}
class _LifecycleAwareAppState extends State<LifecycleAwareApp>
with WidgetsBindingObserver {
AppLifecycleState? _notification;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
_notification = state;
});
print('App lifecycle state: $state');
}
@override
Widget build(BuildContext context) {
String statusText = '';
Color statusColor = Colors.grey;
switch (_notification) {
case AppLifecycleState.paused:
statusText = 'App Paused';
statusColor = Colors.orange;
break;
case AppLifecycleState.resumed:
statusText = 'App Resumed';
statusColor = Colors.green;
break;
case AppLifecycleState.inactive:
statusText = 'App Inactive';
statusColor = Colors.blue;
break;
case AppLifecycleState.detached:
statusText = 'App Detached';
statusColor = Colors.red;
break;
default:
statusText = 'Unknown State';
}
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Lifecycle Demo')),
body: Center(
child: Container(
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: statusColor.withOpacity(0.2),
border: Border.all(color: statusColor),
borderRadius: BorderRadius.circular(8.0),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Current State:',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
statusText,
style: TextStyle(
fontSize: 20,
color: statusColor,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
);
}
}
路由和导航
dart
class NavigationExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
);
}
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('First Screen')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/second');
},
child: Text('Go to Second Screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('This is the second screen'),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go Back'),
),
],
),
),
);
}
}
状态管理基础
InheritedWidget
dart
// 数据共享的InheritedWidget
class ThemeInherited extends InheritedWidget {
final AppThemeData themeData;
const ThemeInherited({
Key? key,
required this.themeData,
required Widget child,
}) : super(key: key, child: child);
static ThemeInherited? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ThemeInherited>();
}
@override
bool updateShouldNotify(ThemeInherited oldWidget) {
return themeData != oldWidget.themeData;
}
}
class AppThemeData {
final Color primaryColor;
final Color backgroundColor;
final TextTheme textTheme;
AppThemeData({
this.primaryColor = Colors.blue,
this.backgroundColor = Colors.white,
this.textTheme = const TextTheme(),
});
}
class ThemedWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = ThemeInherited.of(context)?.themeData;
return Container(
color: theme?.backgroundColor,
child: Center(
child: Text(
'Themed Content',
style: TextStyle(color: theme?.primaryColor),
),
),
);
}
}
异步编程
dart
class AsyncExample extends StatefulWidget {
@override
_AsyncExampleState createState() => _AsyncExampleState();
}
class _AsyncExampleState extends State<AsyncExample> {
String _data = 'Loading...';
bool _isLoading = false;
Future<void> _loadData() async {
setState(() {
_isLoading = true;
_data = 'Loading...';
});
try {
// 模拟网络请求
await Future.delayed(Duration(seconds: 2));
final result = await _fetchDataFromNetwork();
setState(() {
_data = result;
_isLoading = false;
});
} catch (e) {
setState(() {
_data = 'Error: $e';
_isLoading = false;
});
}
}
Future<String> _fetchDataFromNetwork() async {
// 模拟网络请求
return Future.value('Data loaded successfully!');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Async Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isLoading)
CircularProgressIndicator()
else
Text(_data, textAlign: TextAlign.center),
SizedBox(height: 20),
ElevatedButton(
onPressed: _loadData,
child: Text('Load Data'),
),
],
),
),
);
}
}
总结
Flutter的核心概念包括:
- Widget系统:一切皆为Widget,通过组合构建UI
- 状态管理:StatefulWidget管理可变状态
- 布局系统:通过容器和布局Widget构建界面
- 渲染机制:高效的渲染引擎和GPU加速
- 异步编程:Future和async/await处理异步操作
- 生命周期管理:组件和应用生命周期回调
理解这些基础概念是掌握Flutter开发的关键,为后续学习高级特性打下坚实基础。