flutter-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFlutter API Reference Guide
Flutter API参考指南
Overview
概述
This skill provides comprehensive guidance on Flutter's API, covering all major libraries and packages in the Flutter SDK. Flutter is Google's UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase.
本技能提供Flutter API的全面指南,涵盖Flutter SDK中的所有主要库和包。Flutter是谷歌的UI工具包,用于通过单一代码库构建原生编译的移动、Web和桌面应用。
Core Flutter Libraries
核心Flutter库
Widgets (flutter/widgets.dart)
Widgets (flutter/widgets.dart)
The foundational widget library that provides the basic building blocks for Flutter apps.
基础组件库,提供Flutter应用的基本构建块。
Basic Widgets
基础组件
dart
import 'package:flutter/widgets.dart';
// Container - A convenience widget combining common painting, positioning, and sizing
Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.symmetric(horizontal: 8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 4.0)],
),
child: Text('Hello Flutter'),
)
// Text - Display text with styling
Text(
'Hello World',
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
)
// Row & Column - Layout widgets
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.star),
Text('Rating'),
Text('4.5'),
],
)
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Title'),
Text('Subtitle'),
],
)
// Stack - Overlay widgets
Stack(
children: [
Container(color: Colors.blue),
Positioned(
top: 10,
left: 10,
child: Text('Overlay'),
),
],
)dart
import 'package:flutter/widgets.dart';
// Container - 整合了常见绘制、定位和尺寸设置的便捷组件
Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.symmetric(horizontal: 8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 4.0)],
),
child: Text('Hello Flutter'),
)
// Text - 带样式的文本显示组件
Text(
'Hello World',
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
)
// Row & Column - 布局组件
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.star),
Text('Rating'),
Text('4.5'),
],
)
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Title'),
Text('Subtitle'),
],
)
// Stack - 组件叠加布局
Stack(
children: [
Container(color: Colors.blue),
Positioned(
top: 10,
left: 10,
child: Text('Overlay'),
),
],
)Layout Widgets
布局组件
dart
// Padding - Add padding around a widget
Padding(
padding: EdgeInsets.all(16.0),
child: Text('Padded text'),
)
// Center - Center a widget
Center(child: Text('Centered'))
// Align - Align widget within parent
Align(
alignment: Alignment.topRight,
child: Icon(Icons.close),
)
// SizedBox - Fixed size box or spacing
SizedBox(
width: 100,
height: 50,
child: ElevatedButton(
onPressed: () {},
child: Text('Button'),
),
)
// Flexible & Expanded - Responsive sizing
Row(
children: [
Flexible(
flex: 2,
child: Container(color: Colors.red),
),
Expanded(
flex: 3,
child: Container(color: Colors.blue),
),
],
)
// Wrap - Flow layout that wraps children
Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: [
Chip(label: Text('Tag 1')),
Chip(label: Text('Tag 2')),
Chip(label: Text('Tag 3')),
],
)dart
// Padding - 为组件添加内边距
Padding(
padding: EdgeInsets.all(16.0),
child: Text('Padded text'),
)
// Center - 居中显示组件
Center(child: Text('Centered'))
// Align - 在父组件内对齐子组件
Align(
alignment: Alignment.topRight,
child: Icon(Icons.close),
)
// SizedBox - 固定尺寸的容器或间距组件
SizedBox(
width: 100,
height: 50,
child: ElevatedButton(
onPressed: () {},
child: Text('Button'),
),
)
// Flexible & Expanded - 响应式尺寸设置
Row(
children: [
Flexible(
flex: 2,
child: Container(color: Colors.red),
),
Expanded(
flex: 3,
child: Container(color: Colors.blue),
),
],
)
// Wrap - 自动换行的流式布局
Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: [
Chip(label: Text('Tag 1')),
Chip(label: Text('Tag 2')),
Chip(label: Text('Tag 3')),
],
)List Widgets
列表组件
dart
// ListView - Scrollable list
ListView(
children: [
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
],
)
// ListView.builder - Efficient for large lists
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text(items[index]));
},
)
// ListView.separated - With separators
ListView.separated(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(title: Text(items[index])),
separatorBuilder: (context, index) => Divider(),
)
// GridView - Grid layout
GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
children: [
Card(child: Center(child: Text('1'))),
Card(child: Center(child: Text('2'))),
Card(child: Center(child: Text('3'))),
Card(child: Center(child: Text('4'))),
],
)
// GridView.builder - Efficient grid
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: items.length,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('Item $index')));
},
)dart
// ListView - 可滚动列表
ListView(
children: [
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
],
)
// ListView.builder - 适用于大型列表的高效构建方式
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text(items[index]));
},
)
// ListView.separated - 带分隔线的列表
ListView.separated(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(title: Text(items[index])),
separatorBuilder: (context, index) => Divider(),
)
// GridView - 网格布局
GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
children: [
Card(child: Center(child: Text('1'))),
Card(child: Center(child: Text('2'))),
Card(child: Center(child: Text('3'))),
Card(child: Center(child: Text('4'))),
],
)
// GridView.builder - 高效网格构建
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: items.length,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('Item $index')));
},
)Material Design (flutter/material.dart)
Material Design (flutter/material.dart)
Flutter's Material Design implementation with widgets following Material Design guidelines.
Flutter的Material Design实现,组件遵循Material Design设计规范。
Material Widgets
Material组件
dart
import 'package:flutter/material.dart';
// Scaffold - Basic material app structure
Scaffold(
appBar: AppBar(
title: Text('My App'),
actions: [
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
body: Center(child: Text('Content')),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(child: Text('Header')),
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
],
),
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
),
)
// Card - Material design card
Card(
elevation: 4.0,
margin: EdgeInsets.all(8.0),
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Text('Card Title', style: Theme.of(context).textTheme.headlineSmall),
SizedBox(height: 8),
Text('Card content goes here'),
],
),
),
)
// Buttons
ElevatedButton(
onPressed: () {},
child: Text('Elevated Button'),
)
TextButton(
onPressed: () {},
child: Text('Text Button'),
)
OutlinedButton(
onPressed: () {},
child: Text('Outlined Button'),
)
IconButton(
icon: Icon(Icons.favorite),
onPressed: () {},
)
FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
)dart
import 'package:flutter/material.dart';
// Scaffold - 基础Material应用结构
Scaffold(
appBar: AppBar(
title: Text('My App'),
actions: [
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
body: Center(child: Text('Content')),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(child: Text('Header')),
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
],
),
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
),
)
// Card - Material设计风格的卡片组件
Card(
elevation: 4.0,
margin: EdgeInsets.all(8.0),
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Text('Card Title', style: Theme.of(context).textTheme.headlineSmall),
SizedBox(height: 8),
Text('Card content goes here'),
],
),
),
)
// 按钮组件
ElevatedButton(
onPressed: () {},
child: Text('Elevated Button'),
)
TextButton(
onPressed: () {},
child: Text('Text Button'),
)
OutlinedButton(
onPressed: () {},
child: Text('Outlined Button'),
)
IconButton(
icon: Icon(Icons.favorite),
onPressed: () {},
)
FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
)Form Widgets
表单组件
dart
// TextField - Text input
TextField(
decoration: InputDecoration(
labelText: 'Enter your name',
hintText: 'John Doe',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
onChanged: (value) {
print('Text changed: $value');
},
)
// Form with validation
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter email';
}
if (!value.contains('@')) {
return 'Please enter valid email';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Process form
}
},
child: Text('Submit'),
),
],
),
)
// Checkbox
Checkbox(
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value ?? false;
});
},
)
// Radio buttons
Column(
children: [
RadioListTile<String>(
title: Text('Option 1'),
value: 'option1',
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
),
RadioListTile<String>(
title: Text('Option 2'),
value: 'option2',
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
),
],
)
// Switch
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
});
},
)
// Slider
Slider(
value: currentValue,
min: 0,
max: 100,
divisions: 10,
label: currentValue.round().toString(),
onChanged: (value) {
setState(() {
currentValue = value;
});
},
)dart
// TextField - 文本输入组件
TextField(
decoration: InputDecoration(
labelText: 'Enter your name',
hintText: 'John Doe',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
onChanged: (value) {
print('Text changed: $value');
},
)
// 带验证的表单
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter email';
}
if (!value.contains('@')) {
return 'Please enter valid email';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// 处理表单
}
},
child: Text('Submit'),
),
],
),
)
// 复选框
Checkbox(
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value ?? false;
});
},
)
// 单选按钮
Column(
children: [
RadioListTile<String>(
title: Text('Option 1'),
value: 'option1',
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
),
RadioListTile<String>(
title: Text('Option 2'),
value: 'option2',
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value!;
});
},
),
],
)
// 开关组件
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
});
},
)
// 滑块组件
Slider(
value: currentValue,
min: 0,
max: 100,
divisions: 10,
label: currentValue.round().toString(),
onChanged: (value) {
setState(() {
currentValue = value;
});
},
)Dialogs & Sheets
对话框与底部面板
dart
// AlertDialog
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Confirm Action'),
content: Text('Are you sure you want to proceed?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
),
TextButton(
onPressed: () {
// Perform action
Navigator.pop(context);
},
child: Text('Confirm'),
),
],
),
)
// SnackBar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Action completed'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Undo action
},
),
duration: Duration(seconds: 3),
),
)
// Bottom Sheet
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
height: 200,
child: Column(
children: [
ListTile(
leading: Icon(Icons.share),
title: Text('Share'),
onTap: () {},
),
ListTile(
leading: Icon(Icons.link),
title: Text('Copy link'),
onTap: () {},
),
],
),
);
},
)
// Date Picker
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
).then((date) {
if (date != null) {
print('Selected date: $date');
}
});
// Time Picker
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((time) {
if (time != null) {
print('Selected time: $time');
}
});dart
// 警告对话框
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Confirm Action'),
content: Text('Are you sure you want to proceed?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
),
TextButton(
onPressed: () {
// 执行操作
Navigator.pop(context);
},
child: Text('Confirm'),
),
],
),
)
// 提示条
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Action completed'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// 撤销操作
},
),
duration: Duration(seconds: 3),
),
)
// 底部面板
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
height: 200,
child: Column(
children: [
ListTile(
leading: Icon(Icons.share),
title: Text('Share'),
onTap: () {},
),
ListTile(
leading: Icon(Icons.link),
title: Text('Copy link'),
onTap: () {},
),
],
),
);
},
)
// 日期选择器
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
).then((date) {
if (date != null) {
print('Selected date: $date');
}
});
// 时间选择器
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((time) {
if (time != null) {
print('Selected time: $time');
}
});Cupertino (flutter/cupertino.dart)
Cupertino (flutter/cupertino.dart)
iOS-style widgets following Apple's Human Interface Guidelines.
dart
import 'package:flutter/cupertino.dart';
// CupertinoApp - iOS-style app
CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('iOS App'),
),
child: Center(child: Text('Content')),
),
)
// Cupertino Buttons
CupertinoButton(
child: Text('iOS Button'),
onPressed: () {},
)
CupertinoButton.filled(
child: Text('Filled Button'),
onPressed: () {},
)
// Cupertino Dialog
showCupertinoDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text('Alert'),
content: Text('This is an iOS-style alert'),
actions: [
CupertinoDialogAction(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
CupertinoDialogAction(
isDestructiveAction: true,
child: Text('Delete'),
onPressed: () {
// Delete action
Navigator.pop(context);
},
),
],
),
)
// Cupertino Picker
CupertinoPicker(
itemExtent: 32.0,
onSelectedItemChanged: (index) {
print('Selected: $index');
},
children: [
Text('Option 1'),
Text('Option 2'),
Text('Option 3'),
],
)
// Cupertino Sliver Navigation Bar
CupertinoPageScaffold(
child: CustomScrollView(
slivers: [
CupertinoSliverNavigationBar(
largeTitle: Text('Large Title'),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 50,
),
),
],
),
)遵循Apple人机界面指南的iOS风格组件。
dart
import 'package:flutter/cupertino.dart';
// CupertinoApp - iOS风格应用
CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('iOS App'),
),
child: Center(child: Text('Content')),
),
)
// Cupertino按钮
CupertinoButton(
child: Text('iOS Button'),
onPressed: () {},
)
CupertinoButton.filled(
child: Text('Filled Button'),
onPressed: () {},
)
// Cupertino对话框
showCupertinoDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text('Alert'),
content: Text('This is an iOS-style alert'),
actions: [
CupertinoDialogAction(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
CupertinoDialogAction(
isDestructiveAction: true,
child: Text('Delete'),
onPressed: () {
// 删除操作
Navigator.pop(context);
},
),
],
),
)
// Cupertino选择器
CupertinoPicker(
itemExtent: 32.0,
onSelectedItemChanged: (index) {
print('Selected: $index');
},
children: [
Text('Option 1'),
Text('Option 2'),
Text('Option 3'),
],
)
// Cupertino滑动导航栏
CupertinoPageScaffold(
child: CustomScrollView(
slivers: [
CupertinoSliverNavigationBar(
largeTitle: Text('Large Title'),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 50,
),
),
],
),
)Navigation (flutter/material.dart)
导航 (flutter/material.dart)
dart
// Basic navigation
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
// Pop back
Navigator.pop(context);
// Named routes
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
'/settings': (context) => SettingsScreen(),
},
);
// Navigate to named route
Navigator.pushNamed(context, '/details');
// Pass arguments
Navigator.pushNamed(
context,
'/details',
arguments: {'id': 123, 'title': 'Item'},
);
// Receive arguments
class DetailsScreen extends StatelessWidget {
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as Map;
return Scaffold(
appBar: AppBar(title: Text(args['title'])),
body: Text('ID: ${args['id']}'),
);
}
}
// Replace route
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
);
// Remove all and push
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
(route) => false,
);
// Return data from screen
// On second screen
Navigator.pop(context, 'Result data');
// On first screen
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
print('Result: $result');dart
// 基础导航
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
// 返回上一页
Navigator.pop(context);
// 命名路由
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
'/settings': (context) => SettingsScreen(),
},
);
// 跳转到命名路由
Navigator.pushNamed(context, '/details');
// 传递参数
Navigator.pushNamed(
context,
'/details',
arguments: {'id': 123, 'title': 'Item'},
);
// 接收参数
class DetailsScreen extends StatelessWidget {
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as Map;
return Scaffold(
appBar: AppBar(title: Text(args['title'])),
body: Text('ID: ${args['id']}'),
);
}
}
// 替换当前路由
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
);
// 移除所有路由并跳转
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
(route) => false,
);
// 从页面返回数据
// 在第二个页面
Navigator.pop(context, 'Result data');
// 在第一个页面
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
print('Result: $result');Animation (flutter/animation.dart)
动画 (flutter/animation.dart)
dart
import 'package:flutter/animation.dart';
// AnimationController
class AnimatedWidget extends StatefulWidget {
_AnimatedWidgetState createState() => _AnimatedWidgetState();
}
class _AnimatedWidgetState extends State<AnimatedWidget>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 0, end: 300).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
);
_controller.forward();
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Container(
width: _animation.value,
height: _animation.value,
color: Colors.blue,
);
},
);
}
}
// Implicit animations
AnimatedContainer(
duration: Duration(milliseconds: 300),
width: isExpanded ? 200 : 100,
height: isExpanded ? 200 : 100,
color: isExpanded ? Colors.blue : Colors.red,
curve: Curves.easeInOut,
)
AnimatedOpacity(
opacity: isVisible ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
child: Container(color: Colors.blue),
)
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: isTop ? 0 : 100,
left: isLeft ? 0 : 100,
child: Container(width: 50, height: 50, color: Colors.red),
)
// Hero animation
// On first screen
Hero(
tag: 'hero-image',
child: Image.network('url'),
)
// On second screen
Hero(
tag: 'hero-image',
child: Image.network('url'),
)
// TweenAnimationBuilder
TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: 1),
duration: Duration(seconds: 1),
builder: (context, value, child) {
return Opacity(
opacity: value,
child: Transform.scale(
scale: value,
child: child,
),
);
},
child: Container(width: 100, height: 100, color: Colors.blue),
)dart
import 'package:flutter/animation.dart';
// 动画控制器
class AnimatedWidget extends StatefulWidget {
_AnimatedWidgetState createState() => _AnimatedWidgetState();
}
class _AnimatedWidgetState extends State<AnimatedWidget>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 0, end: 300).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
);
_controller.forward();
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Container(
width: _animation.value,
height: _animation.value,
color: Colors.blue,
);
},
);
}
}
// 隐式动画
AnimatedContainer(
duration: Duration(milliseconds: 300),
width: isExpanded ? 200 : 100,
height: isExpanded ? 200 : 100,
color: isExpanded ? Colors.blue : Colors.red,
curve: Curves.easeInOut,
)
AnimatedOpacity(
opacity: isVisible ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
child: Container(color: Colors.blue),
)
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: isTop ? 0 : 100,
left: isLeft ? 0 : 100,
child: Container(width: 50, height: 50, color: Colors.red),
)
// Hero动画
// 在第一个页面
Hero(
tag: 'hero-image',
child: Image.network('url'),
)
// 在第二个页面
Hero(
tag: 'hero-image',
child: Image.network('url'),
)
// Tween动画构建器
TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: 1),
duration: Duration(seconds: 1),
builder: (context, value, child) {
return Opacity(
opacity: value,
child: Transform.scale(
scale: value,
child: child,
),
);
},
child: Container(width: 100, height: 100, color: Colors.blue),
)Gestures (flutter/gestures.dart)
手势 (flutter/gestures.dart)
dart
// GestureDetector
GestureDetector(
onTap: () => print('Tapped'),
onDoubleTap: () => print('Double tapped'),
onLongPress: () => print('Long pressed'),
onPanUpdate: (details) {
print('Pan: ${details.delta}');
},
onScaleUpdate: (details) {
print('Scale: ${details.scale}');
},
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(child: Text('Touch me')),
),
)
// InkWell - Material ripple effect
InkWell(
onTap: () {},
onLongPress: () {},
splashColor: Colors.blue.withOpacity(0.3),
child: Container(
padding: EdgeInsets.all(16),
child: Text('Tap me'),
),
)
// Dismissible - Swipe to dismiss
Dismissible(
key: Key(item.id),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 16),
child: Icon(Icons.delete, color: Colors.white),
),
onDismissed: (direction) {
// Remove item
},
child: ListTile(title: Text(item.title)),
)
// Draggable
Draggable<String>(
data: 'Item data',
child: Container(
width: 100,
height: 100,
color: Colors.blue,
child: Center(child: Text('Drag me')),
),
feedback: Material(
elevation: 4,
child: Container(
width: 100,
height: 100,
color: Colors.blue.withOpacity(0.5),
child: Center(child: Text('Dragging')),
),
),
childWhenDragging: Container(
width: 100,
height: 100,
color: Colors.grey,
),
)
// DragTarget
DragTarget<String>(
builder: (context, candidateData, rejectedData) {
return Container(
width: 200,
height: 200,
color: candidateData.isEmpty ? Colors.grey : Colors.green,
child: Center(child: Text('Drop here')),
);
},
onWillAccept: (data) => true,
onAccept: (data) {
print('Received: $data');
},
)dart
// 手势检测器
GestureDetector(
onTap: () => print('Tapped'),
onDoubleTap: () => print('Double tapped'),
onLongPress: () => print('Long pressed'),
onPanUpdate: (details) {
print('Pan: ${details.delta}');
},
onScaleUpdate: (details) {
print('Scale: ${details.scale}');
},
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(child: Text('Touch me')),
),
)
// InkWell - Material涟漪效果
InkWell(
onTap: () {},
onLongPress: () {},
splashColor: Colors.blue.withOpacity(0.3),
child: Container(
padding: EdgeInsets.all(16),
child: Text('Tap me'),
),
)
// Dismissible - 滑动删除
Dismissible(
key: Key(item.id),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 16),
child: Icon(Icons.delete, color: Colors.white),
),
onDismissed: (direction) {
// 移除项
},
child: ListTile(title: Text(item.title)),
)
// 可拖拽组件
Draggable<String>(
data: 'Item data',
child: Container(
width: 100,
height: 100,
color: Colors.blue,
child: Center(child: Text('Drag me')),
),
feedback: Material(
elevation: 4,
child: Container(
width: 100,
height: 100,
color: Colors.blue.withOpacity(0.5),
child: Center(child: Text('Dragging')),
),
),
childWhenDragging: Container(
width: 100,
height: 100,
color: Colors.grey,
),
)
// 拖拽目标组件
DragTarget<String>(
builder: (context, candidateData, rejectedData) {
return Container(
width: 200,
height: 200,
color: candidateData.isEmpty ? Colors.grey : Colors.green,
child: Center(child: Text('Drop here')),
);
},
onWillAccept: (data) => true,
onAccept: (data) {
print('Received: $data');
},
)State Management
状态管理
dart
// StatefulWidget
class CounterWidget extends StatefulWidget {
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_counter'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
// InheritedWidget
class AppState extends InheritedWidget {
final String username;
final VoidCallback logout;
AppState({
required this.username,
required this.logout,
required Widget child,
}) : super(child: child);
static AppState? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<AppState>();
}
bool updateShouldNotify(AppState oldWidget) {
return username != oldWidget.username;
}
}
// Usage
AppState(
username: 'John',
logout: () {},
child: MyApp(),
)
// Access in child widgets
final appState = AppState.of(context);
print(appState?.username);
// ValueNotifier
class MyWidget extends StatefulWidget {
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
void dispose() {
_counter.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Column(
children: [
ValueListenableBuilder<int>(
valueListenable: _counter,
builder: (context, value, child) {
return Text('Count: $value');
},
),
ElevatedButton(
onPressed: () => _counter.value++,
child: Text('Increment'),
),
],
);
}
}dart
// 有状态组件
class CounterWidget extends StatefulWidget {
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_counter'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
// 继承组件
class AppState extends InheritedWidget {
final String username;
final VoidCallback logout;
AppState({
required this.username,
required this.logout,
required Widget child,
}) : super(child: child);
static AppState? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<AppState>();
}
bool updateShouldNotify(AppState oldWidget) {
return username != oldWidget.username;
}
}
// 使用方式
AppState(
username: 'John',
logout: () {},
child: MyApp(),
)
// 在子组件中访问
final appState = AppState.of(context);
print(appState?.username);
// 值通知器
class MyWidget extends StatefulWidget {
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
void dispose() {
_counter.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Column(
children: [
ValueListenableBuilder<int>(
valueListenable: _counter,
builder: (context, value, child) {
return Text('Count: $value');
},
),
ElevatedButton(
onPressed: () => _counter.value++,
child: Text('Increment'),
),
],
);
}
}Async & Futures
异步与Future
dart
// FutureBuilder
FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.hasData) {
return Text('Data: ${snapshot.data}');
}
return Text('No data');
},
)
// StreamBuilder
StreamBuilder<int>(
stream: counterStream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Count: ${snapshot.data}');
},
)
// Example async function
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
// Example stream
Stream<int> counterStream() async* {
for (int i = 0; i < 10; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}dart
// Future构建器
FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.hasData) {
return Text('Data: ${snapshot.data}');
}
return Text('No data');
},
)
// Stream构建器
StreamBuilder<int>(
stream: counterStream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Count: ${snapshot.data}');
},
)
// 示例异步函数
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
// 示例流
Stream<int> counterStream() async* {
for (int i = 0; i < 10; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}Platform Channels
平台通道
dart
import 'package:flutter/services.dart';
// Method Channel
class BatteryService {
static const platform = MethodChannel('samples.flutter.dev/battery');
Future<int?> getBatteryLevel() async {
try {
final int? result = await platform.invokeMethod('getBatteryLevel');
return result;
} on PlatformException catch (e) {
print("Failed to get battery level: '${e.message}'.");
return null;
}
}
}
// Event Channel
class SensorService {
static const eventChannel = EventChannel('samples.flutter.dev/sensor');
Stream<double> get sensorStream {
return eventChannel.receiveBroadcastStream().map((event) => event as double);
}
}
// Usage
final batteryLevel = await BatteryService().getBatteryLevel();
print('Battery: $batteryLevel%');
SensorService().sensorStream.listen((value) {
print('Sensor value: $value');
});dart
import 'package:flutter/services.dart';
// 方法通道
class BatteryService {
static const platform = MethodChannel('samples.flutter.dev/battery');
Future<int?> getBatteryLevel() async {
try {
final int? result = await platform.invokeMethod('getBatteryLevel');
return result;
} on PlatformException catch (e) {
print("Failed to get battery level: '${e.message}'.");
return null;
}
}
}
// 事件通道
class SensorService {
static const eventChannel = EventChannel('samples.flutter.dev/sensor');
Stream<double> get sensorStream {
return eventChannel.receiveBroadcastStream().map((event) => event as double);
}
}
// 使用方式
final batteryLevel = await BatteryService().getBatteryLevel();
print('Battery: $batteryLevel%');
SensorService().sensorStream.listen((value) {
print('Sensor value: $value');
});Common Patterns
常见模式
Responsive Design
响应式设计
dart
// MediaQuery
final size = MediaQuery.of(context).size;
final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
Container(
width: size.width * 0.8,
height: size.height * 0.5,
)
// LayoutBuilder
LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 600) {
return TabletLayout();
} else {
return MobileLayout();
}
},
)
// OrientationBuilder
OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
crossAxisCount: orientation == Orientation.portrait ? 2 : 4,
children: items,
);
},
)dart
// 媒体查询
final size = MediaQuery.of(context).size;
final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
Container(
width: size.width * 0.8,
height: size.height * 0.5,
)
// 布局构建器
LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 600) {
return TabletLayout();
} else {
return MobileLayout();
}
},
)
// 方向构建器
OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
crossAxisCount: orientation == Orientation.portrait ? 2 : 4,
children: items,
);
},
)Theme Management
主题管理
dart
// Define theme
final lightTheme = ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
textTheme: TextTheme(
headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
bodyMedium: TextStyle(fontSize: 16),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
),
),
);
final darkTheme = ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
);
// Apply theme
MaterialApp(
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
home: HomeScreen(),
)
// Access theme
final theme = Theme.of(context);
Text(
'Styled Text',
style: theme.textTheme.headlineLarge,
)dart
// 定义主题
final lightTheme = ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
textTheme: TextTheme(
headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
bodyMedium: TextStyle(fontSize: 16),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
),
),
);
final darkTheme = ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
);
// 应用主题
MaterialApp(
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
home: HomeScreen(),
)
// 访问主题
final theme = Theme.of(context);
Text(
'Styled Text',
style: theme.textTheme.headlineLarge,
)Performance Optimization
性能优化
dart
// const constructors
const Text('Static text')
const Icon(Icons.home)
// ListView.builder for large lists (already shown above)
// RepaintBoundary
RepaintBoundary(
child: ExpensiveWidget(),
)
// AutomaticKeepAliveClientMixin
class MyWidget extends StatefulWidget {
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with AutomaticKeepAliveClientMixin {
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context); // Must call
return Container();
}
}dart
// const构造函数
const Text('Static text')
const Icon(Icons.home)
// ListView.builder用于大型列表(上文已展示)
// 重绘边界
RepaintBoundary(
child: ExpensiveWidget(),
)
// 自动保持存活混合类
class MyWidget extends StatefulWidget {
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with AutomaticKeepAliveClientMixin {
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context); // 必须调用
return Container();
}
}Resources
资源
This skill includes reference documentation for deeper API exploration:
本技能包含用于深入探索API的参考文档:
references/
references/
- - Comprehensive API reference with additional examples
api_reference.md - Additional library documentation can be added here
For the most up-to-date documentation, visit:
- Official API docs: https://api.flutter.dev/
- Flutter documentation: https://docs.flutter.dev/
- Widget catalog: https://docs.flutter.dev/ui/widgets
- - 包含更多示例的全面API参考
api_reference.md - 更多库文档可添加至此
如需最新文档,请访问:
- 官方API文档:https://api.flutter.dev/
- Flutter文档:https://docs.flutter.dev/
- 组件目录:https://docs.flutter.dev/ui/widgets
Quick Reference
快速参考
Common Imports
常见导入
dart
import 'package:flutter/material.dart'; // Material Design
import 'package:flutter/cupertino.dart'; // iOS style
import 'package:flutter/widgets.dart'; // Base widgets
import 'package:flutter/services.dart'; // Platform servicesdart
import 'package:flutter/material.dart'; // Material Design
import 'package:flutter/cupertino.dart'; // iOS风格
import 'package:flutter/widgets.dart'; // 基础组件
import 'package:flutter/services.dart'; // 平台服务Widget Lifecycle
组件生命周期
dart
initState() // Called once when widget is created
build() // Called when widget needs to be rendered
setState() // Trigger rebuild
dispose() // Called when widget is removeddart
initState() // 组件创建时调用一次
build() // 组件需要渲染时调用
setState() // 触发重建
dispose() // 组件被移除时调用Common Widget Properties
常见组件属性
- - Unique identifier
key - /
child- Child widget(s)children - - Internal spacing
padding - - External spacing
margin - - Visual decoration
decoration - - Size constraints
constraints - - Child alignment
alignment
- - 唯一标识符
key - /
child- 子组件children - - 内边距
padding - - 外边距
margin - - 视觉装饰
decoration - - 尺寸约束
constraints - - 子组件对齐方式
alignment
Layout Guidelines
布局指南
- Use for vertical layout
Column - Use for horizontal layout
Row - Use for overlapping widgets
Stack - Use /
Expandedfor responsive sizingFlexible - Use for scrollable lists
ListView - Use for grid layouts
GridView - Use with Slivers for advanced scrolling
CustomScrollView
- 使用进行垂直布局
Column - 使用进行水平布局
Row - 使用进行组件叠加
Stack - 使用/
Expanded实现响应式尺寸Flexible - 使用创建可滚动列表
ListView - 使用创建网格布局
GridView - 使用结合Slivers实现高级滚动效果
CustomScrollView