import 'package:grpc/grpc.dart'; import 'package:grpc/grpc_or_grpcweb.dart'; import 'package:sampleapp/services/auth/auth.dart'; class AuthInterceptor extends ClientInterceptor { final AuthService authService; AuthInterceptor(this.authService); @override ResponseFuture interceptUnary( ClientMethod method, Q request, CallOptions options, invoker) { final metadata = {}; metadata['authorization'] = 'Bearer ${authService.accessToken}'; options = options.mergedWith(CallOptions(metadata: metadata)); return invoker(method, request, options); } } class GrpcClient { static Client initializeClient( AuthService authService, String host, int port, Client Function(GrpcOrGrpcWebClientChannel, List) clientFactory, ) { final interceptor = AuthInterceptor(authService); final channel = GrpcOrGrpcWebClientChannel.toSingleEndpoint( host: host, port: port, transportSecure: true, ); return clientFactory(channel, [interceptor]); } }