以下是重新整理后的 Flutter 高级用法完整指南,包含详细讲解和优化后的代码示例,涵盖状态管理、自定义绘制、动画、平台交互、性能优化、插件开发等内容。
状态管理是 Flutter 开发中的核心问题之一。Flutter 提供了多种状态管理方案,适合不同复杂度的应用场景。
Provider
是官方推荐的状态管理工具,基于 InheritedWidget
,简单易用。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => CounterModel(),
child: MyApp(),
),
);
}
class CounterModel with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Provider Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: ${context.watch<CounterModel>().count}'),
ElevatedButton(
onPressed: () => context.read<CounterModel>().increment(),
child: Text('Increment'),
),
],
),
),
),
);
}
}
ChangeNotifierProvider
:提供状态管理对象。context.watch
:监听状态变化并更新 UI。context.read
:读取状态但不监听变化。使用 CustomPaint
和 Canvas
可以实现高度自定义的 UI 绘制。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('CustomPaint Example')),
body: Center(
child: CustomPaint(
size: Size(200, 200),
painter: MyPainter(),
),
),
),
);
}
}
class MyPainter extends CustomPainter {
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 50, paint);
}
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
CustomPaint
:用于自定义绘制的组件。CustomPainter
:实现绘制逻辑。shouldRepaint
:控制是否需要重绘。Flutter 提供了强大的动画支持,包括隐式动画和显式动画。
使用 AnimatedContainer
实现简单的属性动画。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _expanded = false;
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Implicit Animation Example')),
body: Center(
child: GestureDetector(
onTap: () => setState(() => _expanded = !_expanded),
child: AnimatedContainer(
duration: Duration(seconds: 1),
width: _expanded ? 200 : 100,
height: _expanded ? 200 : 100,
color: Colors.blue,
child: Center(child: Text('Tap Me')),
),
),
),
),
);
}
}
AnimatedContainer
:自动处理属性变化的动画。setState
:触发 UI 更新。使用 AnimationController
和 Tween
实现复杂的动画。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = Tween(begin: 0.0, end: 1.0).animate(_controller);
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Explicit Animation Example')),
body: Center(
child: FadeTransition(
opacity: _animation,
child: FlutterLogo(size: 100),
),
),
),
);
}
}
AnimationController
:控制动画的播放。Tween
:定义动画的起始值和结束值。FadeTransition
:实现透明度动画。通过平台通道(Platform Channels)实现 Flutter 与原生代码的交互。
在 Flutter 中调用 Android 或 iOS 的原生功能。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Platform Channel Example')),
body: Center(
child: ElevatedButton(
onPressed: () async {
const platform = MethodChannel('samples.flutter.dev/battery');
try {
final result = await platform.invokeMethod('getBatteryLevel');
print('Battery Level: $result%');
} on PlatformException catch (e) {
print('Failed: ${e.message}');
}
},
child: Text('Get Battery Level'),
),
),
),
);
}
}
MethodChannel
:用于 Flutter 与原生代码的通信。invokeMethod
:调用原生方法。PlatformException
:处理平台异常。ListView.builder
优化列表对于长列表,使用 ListView.builder
可以避免一次性加载所有子组件。
ListView.builder(
itemCount: 1000,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
);
ListView.builder
:按需构建列表项,提升性能。const
构造函数尽可能使用 const
构造函数,减少不必要的重建。
const Text('Hello, World!');
const
:避免重复创建相同对象,提升性能。Flutter 允许开发者创建自定义插件,扩展 Flutter 的功能。
使用 flutter create --template=plugin
命令创建插件。
flutter create --template=plugin my_plugin
在 android
和 ios
目录中实现原生代码,并通过 MethodChannel
与 Flutter 通信。
使用 flutter_localizations
和 intl
包实现多语言支持。
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0
flutter_localizations
:提供国际化支持。intl
:用于格式化日期、数字等。通过以上优化后的代码和详细讲解,你可以更好地掌握 Flutter 的高级用法,包括状态管理、自定义绘制、动画、平台交互、性能优化等。这些技巧将帮助你构建更高效、更灵活的 Flutter 应用。