Flutter-refactoring global initialization logic

It may be necessary to initialize other logic before the APP runs, such as some third-party services, AutoNavi maps, etc. If you modify main.dartthe file every time main(), the content of this main()method will be more. The solution is to encapsulate this logic into a separate class, and this class is also a global class, so that if there is any content to be shared on multiple interfaces in the future, put the content that needs to be shared into this class for unified management.

insert image description here

Create a dart file casually,app_context.dart

insert image description here
insert image description here

Another situation that needs to be dealt with is that some services may have to be initialized before entering the main page to execute runApp(const MyApp())code. The solution is to return an asynchronous object in the global classFuture

///AppContext.dart 中

class AppContext{
  static Future init() {
    return Future.value();
  }

}
///main.dart 中

void main() {
  AppContext.init().then((value) => runApp(const MyApp()));
}

In this way, if there is logic that needs to be initialized in the future, there is no need to modify the mian file, and all of them are placed in app_context.dart, which is more convenient for project reconstruction.

Guess you like

Origin blog.csdn.net/m0_48259951/article/details/129263387
Recommended