-
大家好,最近在做 Flutter 项目时,尝试了 **RxFlare** 这个轻量级响应式状态管理库,体验非常不错。今天分享一个**简单易懂的计数器 + 用户信息** 小 Demo,适合新手快速上手。
一、什么是 RxFlare?
RxFlare 是一款 **高性能、自动依赖追踪、字段级精准更新** 的 Flutter 状态管理库。它的最大特点是:
- 代码极简(类似 GetX 的 `.obs`)
- 自动追踪依赖,只更新必要部分
- 性能优秀,适合中大型项目
二、添加依赖
dependencies:
rxflare: ^1.5.0 # 请使用最新版本
三、完整可运行 Demo(推荐复制)
import 'package:flutter/material.dart';
import 'package:rxflare/rxflare.dart';void main() {
runApp(const MyApp());
}class MyApp extends StatelessWidget {
const MyApp({super.key});@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RxFlare Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: const HomePage(),
);
}
}class HomePage extends StatelessWidget {
// 定义响应式变量
final count = 0.obs;
final username = "张三".obs;
final age = 25.obs;
final isLiked = false.obs;HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('RxFlare 状态管理 Demo'),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 自动追踪多个变量
Rx(() => Text(
'点击次数:${count.value}',
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
)),const SizedBox(height: 20),
Rx(() => Text(
'用户名:${username.value},年龄:${age.value}',
style: const TextStyle(fontSize: 20),
)),const SizedBox(height: 40),
// 点赞按钮示例
Rx(() => IconButton(
icon: Icon(
isLiked.value ? Icons.favorite : Icons.favorite_border,
color: isLiked.value ? Colors.red : Colors.grey,
size: 50,
),
onPressed: () => isLiked.value = !isLiked.value,
)),const SizedBox(height: 20),
Rx(() => Text(
isLiked.value ? '❤️ 已喜欢' : '♡ 喜欢一下',
style: const TextStyle(fontSize: 18),
)),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
heroTag: 'add',
onPressed: () => count.value++,
child: const Icon(Icons.add),
),
const SizedBox(height: 16),
FloatingActionButton(
heroTag: 'edit',
onPressed: () {
username.value = "李四";
age.value = 28;
},
child: const Icon(Icons.edit),
),
],
),
);
}
}
#### 四、核心用法总结
1. 声明响应式变量:`xxx.obs`(支持 `int`、`String`、`bool`、`List`、`Map` 等)
2. 响应式 UI:用 `Rx(() => Widget)` 包裹即可自动追踪
3. 修改状态:直接 `xxx.value = 新值` 即可触发更新
五、优点体验
- 代码量少:相比 Bloc 减少大量模板代码
- 性能好:只更新依赖的 Widget,不会全页面重建
- 上手快:几分钟就能跑通