initEasyApp function

Future<void> initEasyApp({
  1. bool? logToFile,
  2. VoidCallback? appBaseURLChangedCallback,
  3. void customExceptionReport(
    1. Object exception,
    2. StackTrace? stackTrace
    )?,
  4. String? singleFileSizeLimit,
  5. int? singleFileHourLimit,
})

可切环境、查看日志 additional arguments: --dart-define=app-debug-flag=true flutter run --release --dart-define=app-debug-flag=true

Implementation

Future<void> initEasyApp({
  bool? logToFile,
  VoidCallback? appBaseURLChangedCallback,
  void Function(Object exception, StackTrace? stackTrace)?
      customExceptionReport,
  String? singleFileSizeLimit,
  int? singleFileHourLimit,
}) async {
  /// https://api.flutter-io.cn/flutter/dart-core/bool/bool.fromEnvironment.html
  const appDebugFlag = bool.fromEnvironment("app-debug-flag");
  isAppDebugFlag = appDebugFlag;
  _appBaseURLChangedCallback = appBaseURLChangedCallback;

  WidgetsFlutterBinding.ensureInitialized();

  BaseEasyLoading.instance.maskType = BaseEasyLoadingMaskType.black;

  final utils = await Future.wait([
    PackageInfoUtil.init(),
    SharedPreferencesUtil.init(),
  ]);

  if (!isWeb) {
    logToFile ??= isAppDebugFlag;
    logFile = LogFile(
      join((await getAppDocumentsDirectory()).path, "logs"),
      enable: logToFile,
      singleFileSizeLimit: singleFileSizeLimit,
      singleFileHourLimit: singleFileHourLimit,
    );
    logDebug("logFile: ${logFile?.location}");
  }

  void localLogWriter(String text, {bool isError = false}) {
    if (isError) {
      logError(text);
    } else {
      logDebug(text);
    }
  }

  Get.config(
    enableLog: isDebug || isAppDebugFlag,
    logWriterCallback: localLogWriter,
  );

  logInfo("Init: $utils");
  final network = await initSelectedBaseURLType();
  logInfo("Network: $network $kBaseURLType");

  // 清除分享图片缓存
  clearShareDirectory();

  if (customExceptionReport != null) {
    // 先将 onError 保存起来
    var onError = FlutterError.onError;
    // onError是FlutterError的一个静态属性,它有一个默认的处理方法 dumpErrorToConsole
    FlutterError.onError = (errorDetails) {
      customExceptionReport.call(errorDetails.exception, errorDetails.stack);
      // 调用默认的onError处理
      onError?.call(errorDetails);
    };
    // 官方推荐使用
    PlatformDispatcher.instance.onError = (error, stack) {
      customExceptionReport.call(error, stack);
      logError("$error\n$stack");
      return true;
    };
  }
}