当前位置:网站首页>Using geTx to build a more elegant structure of flutter pages

Using geTx to build a more elegant structure of flutter pages

2022-06-22 23:52:00 InfoQ

Preface

App  Most of the pages will involve data loading 、 error 、 No data and normal status , At the beginning, we may enumerate the status of data acquisition with  
if...else
  perhaps  
switch
  To display different  
Widget
, In this way, the code will appear ugly , For example, the following code :

if (PersonalController.to.loadingStatus == LoadingStatus.loading) {
 return Center(
 child: Text(' Loading ...'),
 );
}
if (PersonalController.to.loadingStatus == LoadingStatus.failed) {
 return Center(
 child: Text(' request was aborted '),
 );
}
//  The normal state
PersonalEntity personalProfile = PersonalController.to.personalProfile;
return Stack(
 ...
);

This situation is really not elegant , stay  GetX  Provides a kind of  
StateMixin
  The way to solve this problem .

StateMixin

StateMixin
  yes  GetX  A definition of  
mixin
, Page data loading status can be mixed into the status data , The following states are included: :

  • RxStatus.loading()
    : Loading ;
  • RxStatus.success()
    : Loading successful ;
  • RxStatus.error([String? message])
    : Loading failed , Can carry an error message  
    message
    ;
  • RxStatus.empty()
    : No data .

StateMixin  Can be used as follows :

class XXXController extends GetxController
 with StateMixin<T> {
}

among  T  For the actual state class , For example, in our previous article  PersonalEntity, Can be defined as :

class PersonalMixinController extends GetxController
 with StateMixin<PersonalEntity> {
}

then
StateMixin
  Provides a  
change
  Method is used to pass status data and status to the page .

void change(T? newState, {RxStatus? status})

among  
newState
  Is the new status data ,
status
  That's what we said above 4 States . This method will notify  
Widget
  Refresh .

GetView

GetX  Provides a quick  
Widget
  Used to access... In the container  
controller
, namely  
GetView
.
GetView
It's an inheritance  
StatelessWidget
The abstract class of , It's easy to implement , It just defines an acquisition  
controller
  Of  
get
  attribute .

abstract class GetView<T> extends StatelessWidget {
 const GetView({Key? key}) : super(key: key);

 final String? tag = null;

 T get controller => GetInstance().find<T>(tag: tag)!;

 @override
 Widget build(BuildContext context);
}

By inheritance  
GetView
, You can use it directly
controller.obx
Build the interface , and  
controller.obx
  The biggest feature is for  
RxStatus
  Of 4 The four states define four properties respectively :

Widget obx(
 NotifierBuilder<T?> widget, {
 Widget Function(String? error)? onError,
 Widget? onLoading,
 Widget? onEmpty,
})

  • NotifierBuilder<T?> widget: It's actually a variable that carries a state , Functions that return to the normal interface ,NotifierBuilder<T?> Is defined as follows . With this method, you can use state variables to build a normal interface .

typedef NotifierBuilder<T> = Widget Function(T state);

  • onError
    : Corresponding to the error  
    Widget
    Building functions , Error messages can be used  
    error
    .
  • onLoading
    : Corresponding to when loading  
    Widget
    ;
  • onEmpty
    : When the data is empty  
    Widget
    .


In this way, it can automatically according to  
change
Method specified  
RxStatus
  To build different states  UI  Interface , Thus avoiding the ugly  
if...else
  or  
switch
  sentence . For example, our personal homepage , You can write in the following way , Does it feel clearer and fresher ?

class PersonalHomePageMixin extends GetView<PersonalMixinController> {
 PersonalHomePageMixin({Key? key}) : super(key: key);
 @override
 Widget build(BuildContext context) {
 return controller.obx(
 (personalEntity) => _PersonalHomePage(personalProfile: personalEntity!),
 onLoading: Center(
 child: CircularProgressIndicator(),
 ),
 onError: (error) => Center(
 child: Text(error!),
 ),
 onEmpty: Center(
 child: Text(' Temporarily no data '),
 ),
 );
 }
}

Corresponding PersonalMixinController The code for is as follows :

class PersonalMixinController extends GetxController
 with StateMixin<PersonalEntity> {
 final String userId;
 PersonalMixinController({required this.userId});

 @override
 void onReady() {
 getPersonalProfile(userId);
 super.onReady();
 }

 void getPersonalProfile(String userId) async {
 change(null, status: RxStatus.loading());
 var personalProfile = await JuejinService().getPersonalProfile(userId);
 if (personalProfile != null) {
 change(personalProfile, status: RxStatus.success());
 } else {
 change(null, status: RxStatus.error(' Failed to obtain personal information '));
 }
 }
}

Controller  The construction of

from  GetView  You can see the source code of ,Controller  Is obtained from the container , That's what you need to use  GetX  The container of , In the use of  Controller  Previously registered to  GetX  In the container .

Get.lazyPut<PersonalMixinController>(
 () => PersonalMixinController(userId: '70787819648695'),
);

summary

This article introduces the use of
GetX
  Of  
StateMixin
Way to build a more elegant page structure , adopt
controller.obx
  The parameter configuration of different states corresponds to different components . According to  
RxStatus
  State automatic switching component , Instead of writing ugly  
if...else
  or  
switch
  sentence . Of course , The premise of using this method is that you need to  
GetX
  Build in the container of  
controller
  object , The source code of this article has been uploaded to :
GetX  State management source code
. In fact, there are other benefits to using containers , A typical application is dependency injection (Dependency Injection, abbreviation DI), Next, we will use two articles to introduce the concept and specific applications of dependency injection .
null
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222132521237.html