buyProduct static method

Future<void> buyProduct(
  1. String productId,
  2. void onResult(
    1. bool success,
    2. TransactionData? transaction,
    3. String? errorMessage
    ), {
  3. String? uuid,
})

Implementation

static Future<void> buyProduct(
  String productId,
  void Function(bool success, TransactionData? transaction,
          String? errorMessage)
      onResult, {
  String? uuid,
}) async {
  try {
    final Map<String, dynamic> params = {'productId': productId};

    // 只有当uuid非空时才添加到参数中
    if (uuid != null && uuid.isNotEmpty) {
      params['uuid'] = uuid;
    }

    final dynamic result = await _channel.invokeMethod('buyProduct', params);

    // 明确将结果转换为Map<String, dynamic>
    final Map<String, dynamic> resultMap = Map<String, dynamic>.from(result);

    // 成功,调用回调函数,传入success=true、转换后的结果和null作为错误消息
    onResult(true, TransactionData.fromMap(resultMap), null);
  } on PlatformException catch (e) {
    // 如果有平台异常,则调用回调函数,传入success=false、null作为交易和错误消息
    onResult(false, null, e.message);
  } catch (e) {
    // 对于任何其他类型的错误,调用回调函数,传入success=false、null作为交易和通用错误消息
    onResult(false, null, '发生意外错误: $e');
  }
}