用了两年的flutter,有了一些心得,不虚头巴脑,只求实战有用,以供学习或使用flutter的小伙伴参考,学习尚浅,如有不正确的地方还望各路大神指正,以免误人子弟,在此拜谢~(原创不易,转发请标注来源和作者)
注意:无特殊说明,flutter版本为3.0+
讲完了基础工具的封装,那么我们从今天来看下实战中如何组织项目结构。
一.什么是Getx
两年多以前,决定使用Flutter对旧项目进行改造时候,在诸多Flutter框架中(当时有比较流行的Provider状态管理框架,咸鱼开源Fish Redux和BloC)选择了尚不成熟的Getx,当时的Github的star量只有几百和使用人数都相对较少(现在Getx的star超过7.3k),算是见证了它的成长,可见是金子总会被发现。
GetX 是 Flutter 上的一个轻量且强大的解决方案:高性能的状态管理、智能的依赖注入和便捷的路由管理。这些也是它的特色
废话不多说,我们看下如何在实战中使用Getx。
二.使用Getx进行路由管理
Getx提供了一个GetMaterialApp,这个是对MaterialApp的一个封装,可以便捷的配置项目,我们通常这样使用
GetMaterialApp(
onInit: () async {
//项目初始化进行配置
},
debugShowCheckedModeBanner: false,
// theme: appThemeData,
locale: const Locale('zh', 'CN'),
fallbackLocale: const Locale('en', 'US'),
// 添加一个回调语言选项,以备上面指定的语言翻译不存在
defaultTransition: Transition.rightToLeft,
getPages: Pages.pages,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [Locale('en', 'US'), Locale('zh', 'CN')],
initialRoute: Routes.splashPage,
navigatorObservers: [FlutterSmartDialog.observer],
builder: FlutterSmartDialog.init(
toastBuilder: (String msg) {
return customToastWidget(msg);
},
loadingBuilder: (String msg) {
return customLoadingWidget(msg);
},
),
)
其中有getPages和initialRoute,我么知道一个配置项目所有路由页面,一个是项目初始化跳转的页面,一般是闪屏页。
我们知道通常app有非常多的页面,那么怎么更好的组织页面呢?我们可以根据模块进行页面划分。所以我们的Pages可以这样拆写
abstract class AppPages {
static final pages = [
...UsersPages.pages,//用户相关页面
...OrdersPages.pages,//订单相关页面
...GoodsPages.pages,//商品相关页面
...CustomerPages.pages,//客户相关页面
...
];
}
那么在新建的页面中,例如UserPages中可以这样写,那么就把路由拆解开来了
abstract class UsersPages {
static final pages = [
GetPage(
name: Routes.splashPage,
page: () => SplashView(),
binding: SplashBinding(),
),
GetPage(
name: Routes.login,
page: () => LoginView(),
binding: LoginBinding(),
)}
三.使用Getx Bindings依赖注入
不管是写web前端,还是Android或者ios,面对复杂的页面我们都希望页面(UI)和实现(逻辑)进行分离,那么常用的模式有MVC,MVVM等进行抽离,那么在Flutter中我们可以用同样的方式组织项目。
如上图,一个闪屏页面,我们分为bingdings,controllers,views,widget。
bingdings:绑定controller,动态注入
controllers:页面的逻辑实现
views:页面的主要UI
widget:页面用到的组件,页面比较复杂时候抽离出来的组件
四.使用Getx进行状态管理
1.如果你监听的是一个值的改变,那么ObxValue就是一个神器
RxInt count = 0.obs;
当count改变的时候,页面中使用
Obx(()=>Text(count.value))
就可以直接刷新页面
2.GetBuilder
GetBuilder<TestController>(
id: 'count',
builder: (ctl) {return Text(ctl.count);
}
那么只需要在count改变的时候使用
update(['count'])
看源码我们知道,update的底层的实现原理,就是实现了ValueListenable,ChangeNotifier,ValueNotifier
/// An object that maintains a list of listeners.
///
/// The listeners are typically used to notify clients that the object has been
/// updated.
///
/// There are two variants of this interface:
///
/// * [ValueListenable], an interface that augments the [Listenable] interface
/// with the concept of a _current value_.
///
/// * [Animation], an interface that augments the [ValueListenable] interface
/// to add the concept of direction (forward or reverse).
///
/// Many classes in the Flutter API use or implement these interfaces. The
/// following subclasses are especially relevant:
///
/// * [ChangeNotifier], which can be subclassed or mixed in to create objects
/// that implement the [Listenable] interface.
///
/// * [ValueNotifier], which implements the [ValueListenable] interface with
/// a mutable value that triggers the notifications when modified.
///
/// The terms "notify clients", "send notifications", "trigger notifications",
/// and "fire notifications" are used interchangeably.
///
/// See also:
///
/// * [AnimatedBuilder], a widget that uses a builder callback to rebuild
/// whenever a given [Listenable] triggers its notifications. This widget is
/// commonly used with [Animation] subclasses, hence its name, but is by no
/// means limited to animations, as it can be used with any [Listenable]. It
/// is a subclass of [AnimatedWidget], which can be used to create widgets
/// that are driven from a [Listenable].
/// * [ValueListenableBuilder], a widget that uses a builder callback to
/// rebuild whenever a [ValueListenable] object triggers its notifications,
/// providing the builder with the value of the object.
/// * [InheritedNotifier], an abstract superclass for widgets that use a
/// [Listenable]'s notifications to trigger rebuilds in descendant widgets
/// that declare a dependency on them, using the [InheritedWidget] mechanism.
/// * [Listenable.merge], which creates a [Listenable] that triggers
/// notifications whenever any of a list of other [Listenable]s trigger their
/// notifications.
abstract class Listenable {