flutter_quic 0.1.0-beta.1
flutter_quic: ^0.1.0-beta.1 copied to clipboard
Next-generation networking for Flutter with QUIC protocol. Faster connections, better mobile performance, and HTTP/3 support built on the battle-tested Quinn library.
Flutter QUIC #
███████╗██╗ ██╗ ██╗████████╗████████╗███████╗██████╗
██╔════╝██║ ██║ ██║╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗
█████╗ ██║ ██║ ██║ ██║ ██║ █████╗ ██████╔╝
██╔══╝ ██║ ██║ ██║ ██║ ██║ ██╔══╝ ██╔══██╗
██║ ███████╗╚██████╔╝ ██║ ██║ ███████╗██║ ██║
╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
██████╗ ██╗ ██╗██╗ ██████╗
██╔═══██╗██║ ██║██║██╔════╝
██║ ██║██║ ██║██║██║
██║▄▄ ██║██║ ██║██║██║
╚██████╔╝╚██████╔╝██║╚██████╗
╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═════╝
🚀 Lightning-Fast • 🔒 Ultra-Secure • 📱 Cross-Platform
🧪 This library is currently in beta. Ready for testing and development - not yet recommended for production use.
A Flutter plugin that brings Google's QUIC protocol (HTTP/3's transport layer) to your mobile and desktop apps. Built on the blazing-fast Quinn Rust library using flutter_rust_bridge.
🤔 What is QUIC? #
QUIC (Quick UDP Internet Connections) is Google's revolutionary transport protocol that powers HTTP/3 and modern web infrastructure.
📜 The Story #
- 2009: Google started experimenting with SPDY protocol to address HTTP limitations
- 2012: Development of QUIC began as research project focused on reducing latency
- 2013: QUIC shipped in Chrome and started powering Google services
- 2018: IETF standardized QUIC as the foundation for HTTP/3
- 2022: Major browsers and CDNs adopted QUIC worldwide
- Today: Powers YouTube, Google Search, Cloudflare, and millions of websites
🎯 Why QUIC Exists #
TCP was designed in 1974 for a different internet. QUIC solves modern web performance problems:
- Head-of-line blocking: TCP's ordered delivery blocks unrelated streams
- Connection setup overhead: Multiple round trips for TCP + TLS handshakes
- Network switching: Connection breaks when moving between WiFi/cellular
- Security integration: Built-in TLS 1.3 rather than layered on top
QUIC was designed specifically for modern web applications and mobile connectivity patterns.
✨ What This Library Supports #
🚀 Core Features #
- ✅ QUIC Client connections with full Quinn power
- ✅ QUIC Server support with TLS certificate management
- ✅ TLS 1.3 security built-in (not optional)
- ✅ Multiple streams over single connection (bi + uni)
- ✅ QUIC datagrams for unreliable messaging
- ✅ Connection migration (WiFi ↔ cellular seamless switching)
- ✅ 0-RTT reconnection for repeat connections
- ✅ No head-of-line blocking - streams are independent
- ✅ Connection pooling and automatic retry logic
- ✅ HTTP-style API for easy adoption
- ✅ Certificate loading and server configuration
📱 Platform Support #
Platform | Status | Notes |
---|---|---|
Android | ✅ Fully Supported | API 21+ |
iOS | ✅ Fully Supported | iOS 11+ |
Windows | ✅ Fully Supported | Windows 10+ |
macOS | ✅ Fully Supported | macOS 10.14+ |
Linux | ✅ Fully Supported | Modern distributions |
Web | ❌ Not Supported | WebTransport planned for future |
🎯 API Design #
- 🎯 Convenience API: HTTP-style interface for 80% of use cases
- ⚡ Core API: Complete 1:1 Quinn mapping for full control
- 🔄 Async/Await: Full Flutter async integration
- 🛡️ Memory Safe: Rust ownership prevents memory leaks
- 📊 Type Safe: Generated bindings with compile-time safety
❌ What We Don't Support (Yet) #
🚧 Current Limitations #
- ❌ WebTransport (web platform browser API, not Quinn)
- ❌ HTTP/3 semantic layer (raw QUIC transport only)
- ❌ Connection resumption across app restarts
- ❌ Advanced TLS certificate validation (CA chains, custom validation)
📋 Roadmap #
- 🚧 Performance optimization (ongoing)
- ⏳ HTTP/3 helpers for common patterns
- ⏳ Advanced TLS configuration options
- ⏳ Connection accept loops for production servers
📦 Installation #
Step 1: Add Dependency #
Add this to your pubspec.yaml
:
dependencies:
flutter_quic: ^0.1.0-beta.1
Or for the latest development version:
dependencies:
flutter_quic:
git:
url: https://github.com/yourusername/flutter_quic.git
ref: main
Step 2: Install #
flutter pub get
Step 3: Platform Setup #
No additional setup required! The library handles Rust compilation automatically.
Step 4: Initialize #
import 'package:flutter_quic/flutter_quic.dart';
void main() async {
// Initialize the Rust library
await RustLib.init();
runApp(MyApp());
}
🚀 Quick Start #
🎯 Convenience API (Recommended) #
Perfect for HTTP-style requests with QUIC speed:
import 'package:flutter_quic/flutter_quic.dart';
// Create a client (handles connection pooling automatically)
final client = await quicClientCreate();
// Make requests like HTTP but with QUIC speed!
try {
final response = await quicClientGet(
client: client,
url: 'https://example.com/api/data'
);
print('Response: ${response.$2}'); // $2 is the response data
} catch (e) {
print('Error: $e');
}
// POST data
final postResult = await quicClientPost(
client: client,
url: 'https://example.com/api/submit',
data: '{"message": "Hello QUIC!"}'
);
⚡ Core API (Advanced) #
For when you need full Quinn power:
import 'package:flutter_quic/flutter_quic.dart';
// Create endpoint
final endpoint = await createClientEndpoint();
// Connect to server
final connectResult = await endpointConnect(
endpoint: endpoint,
addr: '93.184.216.34:443',
serverName: 'example.com'
);
final connection = connectResult.$2; // Extract connection
// Open bidirectional stream
final streamResult = await connectionOpenBi(connection: connection);
final sendStream = streamResult.$2;
final recvStream = streamResult.$3;
// Send data
await sendStreamWriteAll(
stream: sendStream,
data: 'Hello, QUIC!'.codeUnits
);
// Read response
final readResult = await recvStreamReadToEnd(
stream: recvStream,
maxLength: BigInt.from(1024)
);
final responseData = readResult.$2;
🖥️ QUIC Server #
Create full QUIC servers with TLS certificates:
import 'package:flutter_quic/flutter_quic.dart';
// Load your TLS certificates (DER format required)
final certChain = [await File('server.crt.der').readAsBytes()];
final privateKey = await File('server.key.der').readAsBytes();
// Create server configuration
final serverConfig = await serverConfigWithSingleCert(
certChain: certChain,
key: privateKey,
);
// Create and bind server
final serverEndpoint = await createServerEndpoint(
config: serverConfig,
addr: '127.0.0.1:4433',
);
// Server is now ready to accept connections!
// Use the same Core API for handling connections and streams
🔐 Certificate Requirements & Formats
⚠️ Important: QUIC requires TLS certificates in DER format when loading as binary data. The private key must be in PKCS#8 format.
🧪 Development & Testing
For local development, use the included certificate generator:
# In your example/ directory
./generate_certs.sh
This creates self-signed certificates in the correct formats:
server.crt.der
- Certificate in DER formatserver.key.der
- Private key in PKCS#8 DER formatserver.crt
,server.key
- PEM versions for external tools
// Load DER format certificates (recommended for Flutter assets)
final certBytes = await rootBundle.load('certs/server.crt.der');
final keyBytes = await rootBundle.load('certs/server.key.der');
final certChain = [certBytes.buffer.asUint8List()];
final privateKey = keyBytes.buffer.asUint8List().cast<int>().toList();
🚀 Production Certificates
For production QUIC servers, you'll need valid TLS certificates:
// Option 1: Load DER format files (recommended)
final certChain = [await File('path/to/your/cert.der').readAsBytes()];
final privateKey = await File('path/to/your/private.key.der').readAsBytes();
// Option 2: Convert PEM to DER in code (if you have PEM files)
// Note: Requires additional parsing logic for PEM format
// Option 3: Load from secure storage/environment
final certChain = [base64Decode(Platform.environment['TLS_CERT_DER']!)];
final privateKey = base64Decode(Platform.environment['TLS_KEY_DER']!);
📋 Certificate Format Conversion
If you have existing PEM certificates, convert them to DER:
# Convert certificate to DER
openssl x509 -in server.crt -outform DER -out server.crt.der
# Convert private key to PKCS#8 DER
openssl pkey -in server.key -outform DER -out server.key.der
💡 Where to get certificates:
- 🆓 Let's Encrypt - Free automated certificates (convert to DER)
- ☁️ Cloud providers - AWS ACM, Google Cloud SSL, Azure Key Vault
- 🏢 Corporate CA - Your organization's certificate authority
- 🛒 Commercial CAs - DigiCert, GlobalSign, etc.
- 🧪 Development - Use
./generate_certs.sh
for local testing
📊 Performance Comparison #
🏎️ See QUIC in Action #
// ❌ Traditional HTTP - Sequential requests
final stopwatch = Stopwatch()..start();
final response1 = await http.get(Uri.parse('https://api.example.com/users'));
final response2 = await http.get(Uri.parse('https://api.example.com/posts'));
final response3 = await http.get(Uri.parse('https://api.example.com/comments'));
print('HTTP time: ${stopwatch.elapsedMilliseconds}ms');
// ✅ QUIC - Multiplexed streams over one connection
final quicStopwatch = Stopwatch()..start();
final client = await quicClientCreate();
final futures = await Future.wait([
quicClientGet(client: client, url: 'https://api.example.com/users'),
quicClientGet(client: client, url: 'https://api.example.com/posts'),
quicClientGet(client: client, url: 'https://api.example.com/comments'),
]);
print('QUIC time: ${quicStopwatch.elapsedMilliseconds}ms');
print('🚀 QUIC multiplexing: ${futures.length} requests over single connection');
📈 Real-World Benefits #
Scenario | HTTP/1.1 | HTTP/2 | QUIC (This Library) |
---|---|---|---|
Connection setup | 3 RTTs | 2-3 RTTs | 🚀 1 RTT (0-RTT resume) |
Head-of-line blocking | ❌ Severe | ⚠️ TCP level | ✅ Stream independent |
Network switching | ❌ Connection drops | ❌ Connection drops | ✅ Connection migration |
High latency networks | Slower | Better than HTTP/1.1 | 🚀 Up to 2-3x faster* |
Packet loss (5%) | Significant degradation | Some degradation | ✅ Better resilience* |
*Based on real benchmarks from RWTH Aachen University, LiteSpeed, and TQUIC studies
🔧 API Reference #
Convenience API #
QuicClient Operations
// Create client
Future<QuicClient> quicClientCreate()
Future<QuicClient> quicClientCreateWithConfig({required QuicClientConfig config})
// HTTP-style methods
Future<(QuicClient, String)> quicClientGet({required QuicClient client, required String url})
Future<(QuicClient, String)> quicClientPost({required QuicClient client, required String url, required String data})
Future<(QuicClient, String)> quicClientSend({required QuicClient client, required String url, required String data})
// With timeout variants
Future<(QuicClient, String)> quicClientGetWithTimeout({required QuicClient client, required String url})
Future<(QuicClient, String)> quicClientPostWithTimeout({required QuicClient client, required String url, required String data})
// Configuration and management
Future<(QuicClient, QuicClientConfig)> quicClientConfig({required QuicClient client})
Future<QuicClient> quicClientClearPool({required QuicClient client})
Future<QuicClientConfig> quicClientConfigNew()
Configuration Options
class QuicClientConfig {
final int maxConnectionsPerHost; // Default: 10
final int connectTimeoutMs; // Default: 5000ms
final int requestTimeoutMs; // Default: 30000ms
final int retryAttempts; // Default: 3
final int retryDelayMs; // Default: 1000ms
final int keepAliveTimeoutMs; // Default: 60000ms
}
Core API #
Endpoint Management
// Create client endpoint
Future<QuicEndpoint> createClientEndpoint()
// Create server endpoint (NEW!)
Future<QuicEndpoint> createServerEndpoint({
required QuicServerConfig config,
required String addr
})
// Server configuration (NEW!)
Future<QuicServerConfig> serverConfigWithSingleCert({
required List<Uint8List> certChain,
required List<int> key
})
// Connect to server
Future<(QuicEndpoint, QuicConnection)> endpointConnect({
required QuicEndpoint endpoint,
required String addr,
required String serverName
})
Connection Operations
// Stream management
Future<(QuicConnection, QuicSendStream, QuicRecvStream)> connectionOpenBi({required QuicConnection connection})
Future<(QuicConnection, QuicSendStream)> connectionOpenUni({required QuicConnection connection})
// Connection info
Future<(QuicConnection, SocketAddress)> connectionRemoteAddress({required QuicConnection connection})
Future<(QuicConnection, String?)> connectionLocalIp({required QuicConnection connection})
Future<(QuicConnection, BigInt)> connectionRttMillis({required QuicConnection connection})
Future<(QuicConnection, QuicConnectionStats)> connectionStats({required QuicConnection connection})
Stream Operations
// Writing data
Future<(QuicSendStream, BigInt)> sendStreamWrite({required QuicSendStream stream, required List<int> data})
Future<QuicSendStream> sendStreamWriteAll({required QuicSendStream stream, required List<int> data})
Future<QuicSendStream> sendStreamFinish({required QuicSendStream stream})
// Reading data
Future<(QuicRecvStream, Uint8List?)> recvStreamRead({required QuicRecvStream stream, required BigInt maxLength})
Future<(QuicRecvStream, Uint8List)> recvStreamReadToEnd({required QuicRecvStream stream, required BigInt maxLength})
🛡️ Error Handling #
The library provides specific error types for different scenarios:
try {
final client = await quicClientCreate();
final result = await quicClientGet(client: client, url: 'https://example.com');
} on QuicError catch (e) {
switch (e) {
case QuicError.connection(field0: final message):
print('Connection failed: $message');
// Retry with exponential backoff
case QuicError.endpoint(field0: final message):
print('Endpoint error: $message');
// Check network connectivity
case QuicError.stream(field0: final message):
print('Stream error: $message');
// Handle stream-specific issues
case QuicError.timeout(field0: final message):
print('Operation timed out: $message');
// Inform user of slow network
}
}
🎯 Real-World Examples #
📱 Mobile App with Network Switching #
class ApiService {
late QuicClient _client;
Future<void> init() async {
await RustLib.init();
_client = await quicClientCreate();
}
// This automatically handles WiFi <-> cellular switching!
Future<UserProfile> getUserProfile(String userId) async {
try {
final result = await quicClientGet(
client: _client,
url: 'https://api.myapp.com/users/$userId'
);
return UserProfile.fromJson(jsonDecode(result.$2));
} catch (e) {
// QUIC automatically retries on network switches
rethrow;
}
}
}
🎮 Real-time Gaming Data #
class GameClient {
late QuicConnection _connection;
Future<void> connect() async {
final endpoint = await createClientEndpoint();
final result = await endpointConnect(
endpoint: endpoint,
addr: 'game-server.com:7777',
serverName: 'game-server.com'
);
_connection = result.$2;
}
// Multiple concurrent game streams
Future<void> startGameStreams() async {
// Player position updates (high frequency)
final positionStream = await connectionOpenUni(connection: _connection);
// Chat messages (low frequency)
final chatStream = await connectionOpenBi(connection: _connection);
// Game events (medium frequency)
final eventsStream = await connectionOpenBi(connection: _connection);
// All streams are independent - no head-of-line blocking!
}
}
📊 Dashboard with Multiple APIs #
class DashboardService {
late QuicClient _client;
Future<DashboardData> loadDashboard() async {
_client = await quicClientCreate();
// Fetch all data concurrently over QUIC
final results = await Future.wait([
quicClientGet(client: _client, url: 'https://api.com/analytics'),
quicClientGet(client: _client, url: 'https://api.com/notifications'),
quicClientGet(client: _client, url: 'https://api.com/user-activity'),
quicClientGet(client: _client, url: 'https://api.com/system-status'),
]);
return DashboardData(
analytics: jsonDecode(results[0].$2),
notifications: jsonDecode(results[1].$2),
activity: jsonDecode(results[2].$2),
status: jsonDecode(results[3].$2),
);
}
}
🔧 Development & Testing #
Running Tests #
# Rust tests
cd rust && cargo test
# Flutter tests
flutter test
# Integration tests
flutter drive --target=test_driver/app.dart
Building for Different Platforms #
# Android
flutter build apk
# iOS
flutter build ios
# Desktop
flutter build windows
flutter build macos
flutter build linux
🤝 Contributing #
We welcome contributions! This project follows strict quality standards:
🎯 Development Principles #
- No Placeholders: All code must be production-ready
- Real Implementation: No mock or dummy implementations
- Comprehensive Testing: Unit and integration tests required
- Memory Safety: Rust ownership prevents leaks
- Documentation: All public APIs must be documented
📋 Getting Started #
- Fork the repository
- Create a feature branch:
git checkout -b amazing-feature
- Read CONTRIBUTING.md for detailed guidelines
- Make your changes following our standards
- Add tests for new functionality
- Submit a pull request
🧪 Testing Requirements #
- Unit tests for all new functions
- Integration tests for end-to-end flows
- Performance benchmarks for optimizations
- Cross-platform compatibility testing
📜 License #
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments #
- Quinn - The rock-solid QUIC implementation powering this library
- flutter_rust_bridge - Making Rust-Flutter integration seamless
- Google's QUIC team - For revolutionizing internet transport
- IETF QUIC Working Group - For standardizing the protocol
- Rust and Flutter communities - For amazing tooling and support
🚨 Important Notes #
This library is experimental and under active development.
- ✅ Safe for experimentation and learning
- ⚠️ Not recommended for production apps yet
- 🔄 API may change before stable release
- 📝 Documentation evolving as features stabilize
- 🧪 Beta testing with community feedback ongoing
Ready to try QUIC? We'd love your feedback and contributions!
Made with ❤️ for the Flutter community. Bringing the future of internet transport to mobile and desktop apps.