Features

Automatically generate Hawk style method call handlers for your project.

Getting started

Add hawk_meta and hawk_source_gen package dependency to your pubspec.yaml file

dependencies:
  hawk_meta:
dev_dependencies:
  hawk_source_gen:
  build_runner:

Usage

  1. Annotate a class or function with @HawkEntryPoint annotation from hawk_meta package.
class UserInfo {
  final String userId;
  final String userToken;
  final String userName;

  UserInfo(this.userId, this.userToken, this.userName);

  UserInfo.fromMap(Map map)
      : userId = map['userId'] as String,
        userToken = map['userToken'] as String,
        userName = map['userName'] as String;
}

@HawkEntryPoint()
class AuthService {
  Future<UserInfo> login(String userId, String userToken) async {
    await Future.delayed(const Duration(seconds: 2));
    return UserInfo(userId, userToken, 'test');
  }
  
  
}

Note: @HawkEntryPoint annotation can be used on a class or a top level function/getter/setter. If used on a class, all the public methods of the class will be registered as entry points. If you want to skip some elements, use @HawkApi(ignore: true) annotation.

  1. Run flutter pub run build_runner build --delete-conflicting-outputs to generate the code.

The generated code will be placed in .dart_tool/build/generated/{pkg}lib/src file of your project. All of them have a suffix of .hawk.dart. Currently, you need to copy these files to your target folder manually.

  1. Then you can use the generated code to call the entry point.
void testHawk() {
  final handler = HawkMethodCallDispatcher();
  
  // this is unnecessary
  // hawk will automatically to find fromMap/toJson method of type, if it exists.
  // if it is not what you want, you can register a custom fromMap/toMap method.
  handler.registerTypeConverter(
    fromMap: (map) async => UserInfo.fromMap(map),
    toMap: (UserInfo info) => {
      'userId': info.userId,
      'userToken': info.userToken,
      'userName': info.userName,
    },
  );
  
  // this is needed
  handler.registerMethodCallHandler(
    'AuthService',
    instanceGetter: () async => AuthService(),
    handlers: [HawkAuthService.handleHawkMethodCall],
  );
  
  // pass the `handler` to `IntegratedManager`
  IntegratedManager.instance.init(
      // other arguments
      // ...
      caseList: [handler],
  );
}

Libraries

hawk_meta