Flutter Interview Handbook

Networking & Protocols

100%

Networking & Protocols

Mobile networking in Flutter extends beyond basic HTTP calls. Enterprise applications require robust API client architecture (Dio), real-time streaming (WebSockets), high-performance binary RPCs (gRPC with Protocol Buffers), and secure transport layers (SSL Certificate Pinning).


1. Network Protocol Comparison Matrix

ProtocolTransportSerializationLatency / OverheadReal-time?Key Use Case
REST (HTTP/1.1 or 2)TCPJSON / TextModerate (Text parsing)Request-ResponseStandard CRUD APIs
GraphQLHTTP/1.1JSONFlexible (Exact field fetch)SubscriptionsComplex nested data queries
WebSocketsFull-Duplex TCPText / BinaryMinimal (Low framing overhead)YESReal-time chat, trading feeds
gRPCHTTP/2 MultiplexedProtocol Buffers (Binary)Ultra-Low (Compact binary)YES (Bi-directional)Microservices, high-frequency data

2. Advanced REST Client with Dio

Dio is the industry-standard HTTP client for Flutter, supporting interceptors, global configuration, request cancellation, and automatic retries.

Interceptor Auth Refresh Pipeline

Handling HTTP 401 Unauthorized errors requires locking the request queue, refreshing tokens, and retrying the failed request:

import 'package:dio/dio.dart';

final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'));

void setupAuthInterceptors() {
  dio.interceptors.add(
    InterceptorsWrapper(
      onRequest: (options, handler) async {
        final token = await getAccessToken();
        options.headers['Authorization'] = 'Bearer $token';
        return handler.next(options);
      },
      onError: (DioException error, handler) async {
        if (error.response?.statusCode == 401) {
          try {
            // Lock queue & refresh JWT token asynchronously
            dio.lock();
            final newToken = await refreshAuthToken();
            dio.unlock();

            // Retry original request with new token
            error.requestOptions.headers['Authorization'] = 'Bearer $newToken';
            final response = await dio.fetch(error.requestOptions);
            return handler.resolve(response);
          } catch (e) {
            dio.unlock();
            return handler.next(error);
          }
        }
        return handler.next(error);
      },
    ),
  );
}

3. High-Performance Binary RPC: gRPC & Protocol Buffers

gRPC leverages HTTP/2 multiplexing and Protocol Buffers (protobuf) to serialize data into binary buffers rather than human-readable JSON strings.

Why gRPC Outperforms REST on Mobile

  1. Binary Serialization Speed: Parsing binary protobuf fields is up to 6x-10x faster than parsing CPU-heavy JSON strings in Dart.
  2. Compact Payload Size: Protobuf strips field names and uses varint tags, reducing bandwidth consumption by up to 60-80%.
  3. HTTP/2 Multiplexing: Multiple concurrent API requests share a single underlying TCP connection without head-of-line blocking.
// user.proto
syntax = "proto3";

message UserProfileRequest {
  string user_id = 1;
}

message UserProfileResponse {
  string user_id = 1;
  string display_name = 2;
  int32 loyalty_points = 3;
}

4. Security: SSL Certificate Pinning

To protect sensitive mobile applications from Man-In-The-Middle (MITM) attacks (e.g. proxy tools like Charles or Fiddler intercepting SSL traffic using custom root certificates), implement SSL Certificate Pinning.

SHA-256 Public Key Pinning

Hardcode the server’s public key SHA-256 fingerprint into the Dart HTTP SecurityContext:

import 'dart:io';

HttpClient createPinnedHttpClient() {
  final SecurityContext context = SecurityContext(withTrustedRoots: false);
  // Add hardcoded PEM certificate
  // context.setTrustedCertificatesBytes(pemBytes);

  final client = HttpClient(context: context);
  client.badCertificateCallback = (X509Certificate cert, String host, int port) {
    // Validate cert.sha256 fingerprint against hardcoded SHA-256 hash
    final String serverHash = sha256.convert(cert.der).toString();
    return serverHash == 'EXPECTED_SHA256_FINGERPRINT_HASH';
  };
  return client;
}

5. Trade-offs & Production Considerations

  • gRPC Web Proxy Constraints: Standard gRPC uses HTTP/2 framing. Web Flutter builds require a gRPC-Web proxy (like Envoy) to bridge browser HTTP/1.1 constraints.
  • Certificate Rotation Risk: Hardcoding SSL pinned certificates without a remote dynamic fallback key rotation strategy will brick the app when the server certificate expires! Always pin backup CA keys.