Lite State 是一個輕量級的狀態管理解決方案,專為 Flutter 設計,旨在透過最少的樣板程式碼簡化狀態處理。它提供了一種直接的機器基礎方法來管理狀態轉換,使應用程式狀態的追蹤和更新變得簡單且可預測。非常適合中小型應用,強調簡潔性和效能,無需複雜的設定或大量學習。該套件可無縫整合到現有的 Flutter 專案中,並支援所有主要平台。
適用情境
小型應用中的簡單狀態管理
管理UI狀態轉換
輕量級替代方案,用於大型狀態解決方案
即時資料同步
狀態驅動的 UI 更新
主要特色
最小化樣板程式碼
基於機器的狀態邏輯
跨平台支援
與 Flutter 的輕鬆整合
輕量且快速
適合對象
初學者 Flutter 開發者
需要簡單狀態控制的專案
避免使用重型狀態庫的應用
原型與MVP
重視開發速度的團隊
使用建議
不適用於大型應用程式
有限的內建除錯工具
無內建持久性
需要手動序列化狀態
比功能完整的狀態管理器功能更少
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
Flutter Lite State
The litest state machine ever. You don't need to depend on any heavy libraries
if you only need to control state of your widgets.
This state manager is for those who are tired of writing
lots of boilerplate code of states like in case of using BLoC,
or don't want to depend on BuildContext like with using Provider
or just don't want tons of functionality in one place like with using Get.
I personally do like those state managers but I also see their disadvantages in some usecases. They just don't fit some projects. That's why I decided to write LiteState for the projects that need to be up and running in just a couple of minutes
Lite State is very simple and lite. It consists of a single file.
The purpose of LiteState is to make writing and using controllers as
quick and easy as possible. I wish I could do them even simplier
by using reflection, so that one don't even need to instantiate controllers
but unfortunately, Flutter doesn't support mirrors :(
Anyway, just take a look at the example below
You might also like my other packages
flutter_multi_formatter
flutter_instagram_storyboard
Features
Easily controlling the state of your widgets without a need for context. That's it.
Getting started
All your Lite State controllers must be inherited from LiteStateController
generic class. All the magic is happening inside.
Create a controller you need. E.g. an auth controller to check users'
authorization
Add initialization of your controller somewhere in the beginning of your app
e.g. in initState() {} of your main class
voidmain() {
runApp(constMyApp());
}
classMyAppextendsStatefulWidget{
constMyApp({super.key});
@overrideState<MyApp> createState() => _MyAppState();
}
class_MyAppStateextendsState<MyApp> {
@overridevoidinitState() {
/// In this case I've used lazy initialization/// this means the controller will be instantiated when it's first /// used. Pay attention, I've used AuthController type as a key /// in the instantiator Map. This is used internally to look for /// a controller using generic constraints/// In case you want to initialize all your controllers at once/// just use initControllers() instead of initControllersLazy()initControllersLazy({
AuthController:() => AuthController(),
LoaderController:() => LoaderController(),
});
super.initState();
}
@overrideWidgetbuild(BuildContext context) {
returnMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TestPage(),
);
}
}
Just you LiteState builder any where you need
Widgetbuild(BuildContext context) {
returnLiteState<AuthController>(
builder: (BuildContext c, AuthController controller) {
/// ... your code goes here
},
);
}
OR
You can use a single use controller like this
BE AWARE that in this case you controller will be disposed as soon
as LiteState widget, where you pass it, is disposed
The controller like this will override any other controller of the same time
that you might have initialized via initControllers or initControllersLazy
It's also possible to use the same controller type for many widgets. And the controller instances will not
conflict with each other. In this case the setup is almost the same as the above but along with the instance of the controller you need to pass true to the useIsolatedController parameter of the LiteState widget.
classTestPageextendsStatelessWidget{
constTestPage({Key? key}) : super(key: key);
Widget_buildUserName() {
/// I use authController global property here instead of/// calling findController<AuthController>()/// but it does call findController inside. It's just a shorhandreturnText('Welcome, ${authController.userName}');
}
@overrideWidgetbuild(BuildContext context) {
returnLiteState<AuthController>(
builder: (BuildContext c, AuthController controller) {
returnScaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildUserName(),
constSizedBox(height: 20.0),
Button(
isLoading: controller.isLoading,
text: controller.isAuthorized ? 'Log Out' : 'Authorize',
onPressed: () {
/// you can also use a shorthand method fc<AuthController>()/// to do the same. It calls findController internally/// or just write a global function to get it./// e.g. right above AuthController declaration/// AuthController get authController {/// return findController<AuthController>();/// }if (controller.isAuthorized) {
findController<AuthController>().logout();
} else {
findController<AuthController>().authorize();
}
},
),
constPadding(
padding: EdgeInsets.only(
left: 40.0,
right: 40.0,
top: 20.0,
),
child: Text(
'Notice that your authorization is stored across sessions in a persistant local storage. Reload the app and you will see that authorization is still there',
),
),
],
),
),
);
},
);
}
}
Controllers also allow you to easily store and restore
data from shared preferences. When the local data is restored
a controller calls void onLocalStorageInitialied(); method.
You can override it in your controllers to know the exact time
when your local data is ready.
This example shows how you can store and restore auth tokens
/// First you need to create a class that you want to/// be storable / restorable. The class must implement /// LSJsonEncodable interface. It's very simple and is needed /// for a LiteState controller to determin if and instance of the /// class can be serialized according to its rules. /// The interface only contains one method: Map encode(); /// which must be overriden in your classclassAuthDataimplementsLSJsonEncodable{
String type;
String token;
String userName;
AuthData({
requiredthis.type,
requiredthis.token,
requiredthis.userName,
});
@overrideMapencode() {
return {
'type': type,
'token': token,
'userName': userName,
};
}
/// The static method is necessary as a decoder /// so that a controller can understand how to work with your data/// when it meet the data in SharedPreferences/// You can see how it's used belowstaticAuthDatadecode(Map map) {
returnAuthData(
type: map['type'],
token: map['token'],
userName: map['userName'],
);
}
}
Now you need to initialize your decoders. The best place to do it is
right before you initialize your controllers. Somewhere in the beginning of your app
@overridevoidinitState() {
/// Initialize decoders. In this case we only have AuthData decoder/// but you will need to add decoders for every class you want to be encodable / decodableinitJsonDecoders({
AuthData: AuthData.decode,
});
initControllersLazy({
AuthController:() => AuthController(),
LoaderController:() => LoaderController(),
});
super.initState();
}
That's basically it. Now you can simply use it in your controller.
If you want to rebuild only a particular builder, you can give this name to a LiteState instance amd pass the same name to the rebuild('someBuilderName') method. This will trigger only a particular builder. If you don't pass a name, all builders for this controllers that are currently in the widget tree will be rebuilt.
Here's the complete example. As you can see, it uses a few instances of LiteState with the same controller on the same page. But the instances have different names. And when you press a corresponding button, you will see only one print with the related information, which means that only that builder was triggered.
import'package:example/button.dart';
import'package:flutter/material.dart';
import'package:lite_state/lite_state.dart';
classNamedBuildersPageextendsStatefulWidget{
constNamedBuildersPage({super.key});
@overrideState<NamedBuildersPage> createState() => _NamedBuildersPageState();
}
class_NamedBuildersPageStateextendsState<NamedBuildersPage> {
finalNamedBuilderController _controller = NamedBuilderController();
@overrideWidgetbuild(BuildContext context) {
returnScaffold(
appBar: AppBar(
title: constText('Named Builders Page'),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
constSizedBox(
height: 100.0,
),
/// Press one of two buttons and see how only a particular print will work/// While the builders use the same instance of controllerLiteState<NamedBuilderController>(
controller: _controller,
builderName: 'text1',
builder: (BuildContext c, NamedBuilderController controller) {
debugPrint('REBUILD TEXT 1');
returnconstText('Text1');
},
),
constSizedBox(
height: 20.0,
),
LiteState<NamedBuilderController>(
controller: _controller,
builderName: 'text2',
builder: (BuildContext c, NamedBuilderController controller) {
debugPrint('REBUILD TEXT 2');
returnconstText('Text2');
},
),
constSizedBox(
height: 20.0,
),
Button(
text: 'Rebuild Text1',
onPressed: () {
_controller.rebuild('text1');
},
),
Button(
text: 'Rebuild Text2',
onPressed: () {
_controller.rebuild('text2');
},
),
Button(
text: 'Unnamed Rebuild',
onPressed: () {
_controller.rebuild();
},
),
],
),
),
);
}
}
classNamedBuilderControllerextendsLiteStateController<NamedBuilderController> {
@overridevoidreset() {}
@overridevoidonLocalStorageInitialized() {}
}