Flutter状态管理工具插件state_tools的使用
Flutter状态管理工具插件state_tools的使用
State Tools
State Tools 是一个轻量且简单的 Flutter 应用程序状态管理器。
如何简单?
1. 创建你的 StateNotifier
类:
class CounterState extends StateNotifier<int> {
CounterState() : super(0);
void increment() => state += 1;
}
如果你需要对列表进行特定类型的操作:
class CounterState extends ListStateNotifier<int> {
CounterState() : super(List.empty());
void push(int value) => add(value * 2);
[@override](/user/override)
bool filter(int value) => value % 2 == 0;
}
你可以为列表应用过滤器(非强制性)。这个过滤器将在每次列表值更改时应用。此外,ListStateNotifier
提供了一些预构建的帮助修饰符,如:
add(item)
removeFirst(item)
addAll([ list of items ])
removeAll([ list of items ])
2. 在你的小部件中使用 StateBuilder
来与你的 StateNotifier
交互
StateBuilder<int>(
notifier: counterStateInstance,
builder: (context, state) => Text('$state')
)
...
FloatingActionButton(
onPressed: () => counterStateInstance.increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
)
或者,你也可以监听更改并执行与 UI 无关的逻辑:
StateListener<int>(
notifier: counterStateInstance,
listener: (context, state) => print('$state'),
child: const Text('My StateListener')
)
从版本 1.1.0
开始,可以同时构建和监听多个状态,使用 DoubleStateBuilder
, DoubleStateListener
, TripleStateBuilder
和 TripleStateListener
:
DoubleStateBuilder<int, String>(
notifier1: counterStateInstance,
notifier2: textStateInstance,
builder: (context, counter, text) => Text('$counter : $text')
)
...
TripleStateListener<int, String, bool>(
notifier1: counterStateInstance,
notifier2: textStateInstance,
notifier3: boolStateInstance,
listener: (context, counter, text, boolValue) => print('$counter : $text : $boolValue'),
child: const Text('My TripleStateListener')
)
想要更多?
如果你想使用 PersistableStateNotifier
,你可以这样做:
class CounterState extends PersistableStateNotifier<int> {
CounterState() : super(0);
void increment() => state += 1;
[@override](/user/override)
int fromJson(Map<String, dynamic> json) => json['value'] as int;
[@override](/user/override)
Map<String, int> toJson(int state) => {'value': state};
}
感兴趣?
在你的应用程序中添加 state_tools
包:
dependencies:
state_tools: 1.1.1
许可证
Copyright 2024 TMApps
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
完整示例Demo
以下是一个完整的示例代码,展示了如何使用 state_tools
包来管理状态。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:state_tools/state_tools.dart';
import 'injector.dart';
import 'observer.dart';
import 'theme.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
StateUtils.observer = const AppStateObserver();
PersistableStateNotifier.defaultStorage = await StateStorage.build(
storageDirectory: kIsWeb
? StateStorage.webStorageDirectory
: await getTemporaryDirectory(),
);
runApp(Injector(child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) => StateBuilder<ThemeMode>(
notifier: context.themeStore,
builder: (BuildContext context, ThemeMode themeMode) => MaterialApp(
title: 'Flutter - State Manager',
theme: lightTheme,
darkTheme: darkTheme,
themeMode: themeMode,
home: const MyHomePage(title: 'State Manager - Demo'),
debugShowCheckedModeBanner: false,
),
);
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
[@override](/user/override)
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
actions: [
StateBuilder<ThemeMode>(
notifier: context.themeStore,
builder: (context, themeMode) => IconButton(
onPressed: () => context.themeStore.switchTheme(),
icon: Icon(themeMode == ThemeMode.light
? Icons.mode_night_sharp
: Icons.sunny)),
)
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Count Number:'),
StateBuilder<int>(
notifier: context.counterStore,
// buildWhen: (previous, current) => current % 2 == 0,
builder: (BuildContext context, int count) => Text(
'$count',
style: context.theme.textTheme.headlineMedium,
),
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: FloatingActionButton(
onPressed: () => context.counterStore.decrement(),
tooltip: 'Decrement',
child: const Icon(Icons.remove),
),
),
FloatingActionButton(
onPressed: () => context.counterStore.increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
],
),
);
}
更多关于Flutter状态管理工具插件state_tools的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter状态管理工具插件state_tools的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter中使用state_tools
插件的简单示例代码。请注意,state_tools
并非一个广泛认知的标准Flutter插件,因此以下示例假设state_tools
提供了类似状态管理的功能。如果state_tools
实际插件与假设不符,请根据具体文档进行调整。
假设state_tools
插件提供了一些基本的状态管理功能,比如创建状态、监听状态变化等。以下是一个简单的示例,展示如何使用这个插件来管理应用状态。
首先,确保在pubspec.yaml
文件中添加了state_tools
依赖(注意:这只是一个假设的依赖,实际使用时请替换为真实存在的插件):
dependencies:
flutter:
sdk: flutter
state_tools: ^1.0.0 # 假设的版本号
然后,运行flutter pub get
来获取依赖。
接下来,是一个简单的Flutter应用示例,展示如何使用state_tools
进行状态管理:
import 'package:flutter/material.dart';
import 'package:state_tools/state_tools.dart'; // 假设的导入路径
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter State Tools Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// 假设的StateTool实例,用于管理状态
late StateTool<int> counterStateTool;
@override
void initState() {
super.initState();
// 初始化StateTool,初始值为0
counterStateTool = StateTool<int>(initialValue: 0);
// 监听状态变化
counterStateTool.addListener(() {
setState(() {}); // 状态变化时刷新UI
});
}
@override
void dispose() {
// 移除监听器,避免内存泄漏
counterStateTool.removeListener(() {});
super.dispose();
}
void _incrementCounter() {
// 更新状态
counterStateTool.value++;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter State Tools Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${counterStateTool.value}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
在这个示例中,我们假设StateTool
是一个简单的状态管理工具,它接受一个初始值,并允许我们监听状态的变化。当用户点击浮动操作按钮时,状态值会增加,并且UI会自动刷新以反映最新的状态。
请注意,由于state_tools
并非一个真实存在的标准插件,上述代码中的StateTool
类及其方法是假设的。在实际项目中,你需要根据state_tools
插件的文档来调整代码。如果state_tools
插件提供了类似Provider、Riverpod或GetX等插件的功能,那么你需要参考相应的文档来正确实现状态管理。