- Implement Community model for managing community data, including secret handling and PSK derivation. - Create CommunityQrScannerScreen for scanning and joining communities via QR codes. - Develop CommunityStore for persisting community data using SharedPreferences. - Introduce QrCodeDisplay widget for displaying QR codes with customizable options. - Add QrScannerWidget for reusable QR code scanning functionality with validation and controls.chore/offband-rebrand
parent
f790604d23
commit
f4ec732de8
|
After Width: | Height: | Size: 579 KiB |
@ -0,0 +1,243 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart' as crypto;
|
||||
|
||||
/// Represents a community with a shared secret for deriving channel PSKs.
|
||||
///
|
||||
/// A Community is a namespace with a shared secret K (32 random bytes),
|
||||
/// distributed via QR code. Members can create Community Public Channels
|
||||
/// and Community Hashtag Channels that are opaque to outsiders.
|
||||
class Community {
|
||||
/// Unique identifier for local storage
|
||||
final String id;
|
||||
|
||||
/// Display name for the community
|
||||
final String name;
|
||||
|
||||
/// The 32-byte shared secret (K)
|
||||
final Uint8List secret;
|
||||
|
||||
/// Timestamp when the community was created/joined
|
||||
final DateTime createdAt;
|
||||
|
||||
/// List of hashtag channel names (without #) that have been added
|
||||
final List<String> hashtagChannels;
|
||||
|
||||
Community({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.secret,
|
||||
required this.createdAt,
|
||||
List<String>? hashtagChannels,
|
||||
}) : hashtagChannels = hashtagChannels ?? [];
|
||||
|
||||
/// Generate a new community with a random 32-byte secret
|
||||
factory Community.create({
|
||||
required String id,
|
||||
required String name,
|
||||
}) {
|
||||
final random = Random.secure();
|
||||
final secret = Uint8List(32);
|
||||
for (int i = 0; i < 32; i++) {
|
||||
secret[i] = random.nextInt(256);
|
||||
}
|
||||
return Community(
|
||||
id: id,
|
||||
name: name,
|
||||
secret: secret,
|
||||
createdAt: DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Parse a community from QR code JSON data
|
||||
factory Community.fromQrData(String id, String qrData) {
|
||||
final json = jsonDecode(qrData) as Map<String, dynamic>;
|
||||
if (json['type'] != 'meshcore_community') {
|
||||
throw const FormatException('Invalid QR code type');
|
||||
}
|
||||
if (json['v'] != 1) {
|
||||
throw const FormatException('Unsupported QR code version');
|
||||
}
|
||||
|
||||
final name = json['name'] as String;
|
||||
final secretBase64 = json['k'] as String;
|
||||
final secret = base64Url.decode(secretBase64);
|
||||
|
||||
if (secret.length != 32) {
|
||||
throw const FormatException('Invalid secret length');
|
||||
}
|
||||
|
||||
return Community(
|
||||
id: id,
|
||||
name: name,
|
||||
secret: Uint8List.fromList(secret),
|
||||
createdAt: DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Parse a community from storage JSON
|
||||
factory Community.fromJson(Map<String, dynamic> json) {
|
||||
return Community(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
secret: base64Decode(json['secret'] as String),
|
||||
createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at'] as int),
|
||||
hashtagChannels: (json['hashtag_channels'] as List<dynamic>?)
|
||||
?.map((e) => e as String)
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
/// Convert to JSON for storage
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'secret': base64Encode(secret),
|
||||
'created_at': createdAt.millisecondsSinceEpoch,
|
||||
'hashtag_channels': hashtagChannels,
|
||||
};
|
||||
}
|
||||
|
||||
/// Generate QR code JSON payload for sharing
|
||||
String toQrJson() {
|
||||
return jsonEncode({
|
||||
'v': 1,
|
||||
'type': 'meshcore_community',
|
||||
'name': name,
|
||||
'k': base64Url.encode(secret),
|
||||
});
|
||||
}
|
||||
|
||||
/// Derive the public Community ID from the secret.
|
||||
/// This is safe to display/log since it's one-way derived.
|
||||
/// CID = SHA256("community:v1" || K)
|
||||
String get communityId {
|
||||
final data = utf8.encode('community:v1') + secret;
|
||||
final hash = crypto.sha256.convert(data).bytes;
|
||||
return _bytesToHex(Uint8List.fromList(hash));
|
||||
}
|
||||
|
||||
/// Short version of community ID for display (first 8 chars)
|
||||
String get shortCommunityId => communityId.substring(0, 8);
|
||||
|
||||
/// Derive PSK for community public channel.
|
||||
/// PSK = HMAC-SHA256(K, "channel:v1:__public__")[:16]
|
||||
Uint8List deriveCommunityPublicPsk() {
|
||||
final hmac = crypto.Hmac(crypto.sha256, secret);
|
||||
final digest = hmac.convert(utf8.encode('channel:v1:__public__'));
|
||||
return Uint8List.fromList(digest.bytes.sublist(0, 16));
|
||||
}
|
||||
|
||||
/// Derive PSK for community hashtag channel.
|
||||
/// PSK = HMAC-SHA256(K, "channel:v1:" + normalized_name)[:16]
|
||||
Uint8List deriveCommunityHashtagPsk(String hashtag) {
|
||||
final normalized = _normalizeCommunityHashtag(hashtag);
|
||||
final hmac = crypto.Hmac(crypto.sha256, secret);
|
||||
final digest = hmac.convert(utf8.encode('channel:v1:$normalized'));
|
||||
return Uint8List.fromList(digest.bytes.sublist(0, 16));
|
||||
}
|
||||
|
||||
/// Check if QR data is valid community data
|
||||
static bool isValidQrData(String data) {
|
||||
try {
|
||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||
if (json['type'] != 'meshcore_community') return false;
|
||||
if (json['v'] != 1) return false;
|
||||
if (json['name'] == null || (json['name'] as String).isEmpty) {
|
||||
return false;
|
||||
}
|
||||
if (json['k'] == null) return false;
|
||||
final secret = base64Url.decode(json['k'] as String);
|
||||
return secret.length == 32;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a hashtag name for consistent PSK derivation.
|
||||
/// Strips leading #, converts to lowercase, trims whitespace.
|
||||
static String _normalizeCommunityHashtag(String hashtag) {
|
||||
return hashtag.replaceFirst(RegExp(r'^#'), '').toLowerCase().trim();
|
||||
}
|
||||
|
||||
/// Add a hashtag channel to this community's list
|
||||
Community addHashtagChannel(String hashtag) {
|
||||
final normalized = _normalizeCommunityHashtag(hashtag);
|
||||
if (hashtagChannels.contains(normalized)) {
|
||||
return this;
|
||||
}
|
||||
return Community(
|
||||
id: id,
|
||||
name: name,
|
||||
secret: secret,
|
||||
createdAt: createdAt,
|
||||
hashtagChannels: [...hashtagChannels, normalized],
|
||||
);
|
||||
}
|
||||
|
||||
/// Remove a hashtag channel from this community's list
|
||||
Community removeHashtagChannel(String hashtag) {
|
||||
final normalized = _normalizeCommunityHashtag(hashtag);
|
||||
return Community(
|
||||
id: id,
|
||||
name: name,
|
||||
secret: secret,
|
||||
createdAt: createdAt,
|
||||
hashtagChannels: hashtagChannels.where((h) => h != normalized).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of this community with a new secret
|
||||
Community withNewSecret(Uint8List newSecret) {
|
||||
return Community(
|
||||
id: id,
|
||||
name: name,
|
||||
secret: newSecret,
|
||||
createdAt: createdAt,
|
||||
hashtagChannels: hashtagChannels,
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of this community with a regenerated random secret
|
||||
Community withRegeneratedSecret() {
|
||||
final random = Random.secure();
|
||||
final newSecret = Uint8List(32);
|
||||
for (int i = 0; i < 32; i++) {
|
||||
newSecret[i] = random.nextInt(256);
|
||||
}
|
||||
return withNewSecret(newSecret);
|
||||
}
|
||||
|
||||
/// Extract secret from QR data (for updating existing community)
|
||||
static Uint8List? extractSecretFromQrData(String qrData) {
|
||||
try {
|
||||
final json = jsonDecode(qrData) as Map<String, dynamic>;
|
||||
if (json['type'] != 'meshcore_community') return null;
|
||||
if (json['v'] != 1) return null;
|
||||
final secretBase64 = json['k'] as String;
|
||||
final secret = base64Url.decode(secretBase64);
|
||||
if (secret.length != 32) return null;
|
||||
return Uint8List.fromList(secret);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String _bytesToHex(Uint8List bytes) {
|
||||
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Community &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id;
|
||||
|
||||
@override
|
||||
int get hashCode => id.hashCode;
|
||||
}
|
||||
@ -0,0 +1,245 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/community.dart';
|
||||
import '../storage/community_store.dart';
|
||||
import '../widgets/qr_scanner_widget.dart';
|
||||
|
||||
/// Screen for scanning community QR codes to join communities.
|
||||
///
|
||||
/// After successful scan, the user can:
|
||||
/// 1. Join the community (saves to local storage)
|
||||
/// 2. Optionally add the Community Public Channel to the device
|
||||
class CommunityQrScannerScreen extends StatefulWidget {
|
||||
const CommunityQrScannerScreen({super.key});
|
||||
|
||||
@override
|
||||
State<CommunityQrScannerScreen> createState() =>
|
||||
_CommunityQrScannerScreenState();
|
||||
}
|
||||
|
||||
class _CommunityQrScannerScreenState extends State<CommunityQrScannerScreen> {
|
||||
final CommunityStore _communityStore = CommunityStore();
|
||||
bool _isProcessing = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(context.l10n.community_scanQr),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: _isProcessing
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: QrScannerWidget(
|
||||
onScanned: (data) => _handleScannedData(context, data),
|
||||
validator: Community.isValidQrData,
|
||||
onValidationFailed: (_) => _showInvalidQrError(context),
|
||||
instructions: context.l10n.community_scanInstructions,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleScannedData(BuildContext context, String data) async {
|
||||
if (_isProcessing) return;
|
||||
|
||||
setState(() {
|
||||
_isProcessing = true;
|
||||
});
|
||||
|
||||
try {
|
||||
// Parse the community data
|
||||
final community = Community.fromQrData(const Uuid().v4(), data);
|
||||
|
||||
// Check if this community already exists
|
||||
final existing = await _communityStore.findByCommunityId(
|
||||
community.communityId,
|
||||
);
|
||||
|
||||
if (existing != null) {
|
||||
if (context.mounted) {
|
||||
_showAlreadyMemberDialog(context, existing);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Show confirmation dialog
|
||||
if (context.mounted) {
|
||||
await _showJoinConfirmationDialog(context, community);
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.community_invalidQrCode),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isProcessing = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showInvalidQrError(BuildContext context) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.community_invalidQrCode),
|
||||
backgroundColor: Colors.orange,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showAlreadyMemberDialog(BuildContext context, Community community) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(context.l10n.community_alreadyMember),
|
||||
content: Text(
|
||||
context.l10n.community_alreadyMemberMessage(community.name),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(dialogContext);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(context.l10n.common_ok),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showJoinConfirmationDialog(
|
||||
BuildContext context,
|
||||
Community community,
|
||||
) async {
|
||||
bool addPublicChannel = true;
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => StatefulBuilder(
|
||||
builder: (dialogContext, setDialogState) => AlertDialog(
|
||||
title: Text(context.l10n.community_joinTitle),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(context.l10n.community_joinConfirmation(community.name)),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.groups,
|
||||
color: Theme.of(dialogContext).colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
community.name,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(
|
||||
'ID: ${community.shortCommunityId}...',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
value: addPublicChannel,
|
||||
onChanged: (value) {
|
||||
setDialogState(() {
|
||||
addPublicChannel = value ?? true;
|
||||
});
|
||||
},
|
||||
title: Text(context.l10n.community_addPublicChannel),
|
||||
subtitle: Text(context.l10n.community_addPublicChannelHint),
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(context.l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(context.l10n.community_join),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (result == true && context.mounted) {
|
||||
await _joinCommunity(context, community, addPublicChannel);
|
||||
} else if (context.mounted) {
|
||||
// User cancelled - go back
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _joinCommunity(
|
||||
BuildContext context,
|
||||
Community community,
|
||||
bool addPublicChannel,
|
||||
) async {
|
||||
// Save community to local storage
|
||||
await _communityStore.addCommunity(community);
|
||||
|
||||
// Optionally add the community public channel to the device
|
||||
if (addPublicChannel && context.mounted) {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
final nextIndex = _findNextAvailableChannelIndex(connector);
|
||||
|
||||
if (nextIndex != null) {
|
||||
final psk = community.deriveCommunityPublicPsk();
|
||||
final channelName = '${community.name} Public';
|
||||
connector.setChannel(nextIndex, channelName, psk);
|
||||
}
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.community_joined(community.name)),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
|
||||
// Return to previous screen
|
||||
Navigator.pop(context, community);
|
||||
}
|
||||
}
|
||||
|
||||
int? _findNextAvailableChannelIndex(MeshCoreConnector connector) {
|
||||
final usedIndices = connector.channels.map((c) => c.index).toSet();
|
||||
for (int i = 0; i < connector.maxChannels; i++) {
|
||||
if (!usedIndices.contains(i)) return i;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,117 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../models/community.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// Persists communities to local storage using SharedPreferences.
|
||||
///
|
||||
/// Communities are stored as a JSON array under a single key.
|
||||
/// Each community contains its secret K, so this data should
|
||||
/// be considered sensitive (though device encryption handles security).
|
||||
class CommunityStore {
|
||||
static const String _communitiesKey = 'communities_v1';
|
||||
|
||||
/// Load all communities from storage
|
||||
Future<List<Community>> loadCommunities() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final jsonString = prefs.getString(_communitiesKey);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
final jsonList = jsonDecode(jsonString) as List<dynamic>;
|
||||
return jsonList
|
||||
.map((json) => Community.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
// If JSON is corrupted, return empty list
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Save all communities to storage
|
||||
Future<void> saveCommunities(List<Community> communities) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final jsonList = communities.map((c) => c.toJson()).toList();
|
||||
await prefs.setString(_communitiesKey, jsonEncode(jsonList));
|
||||
}
|
||||
|
||||
/// Add a new community
|
||||
Future<void> addCommunity(Community community) async {
|
||||
final communities = await loadCommunities();
|
||||
|
||||
// Check if community with same ID already exists
|
||||
final existingIndex = communities.indexWhere((c) => c.id == community.id);
|
||||
if (existingIndex >= 0) {
|
||||
// Replace existing
|
||||
communities[existingIndex] = community;
|
||||
} else {
|
||||
communities.add(community);
|
||||
}
|
||||
|
||||
await saveCommunities(communities);
|
||||
}
|
||||
|
||||
/// Update an existing community
|
||||
Future<void> updateCommunity(Community community) async {
|
||||
final communities = await loadCommunities();
|
||||
final index = communities.indexWhere((c) => c.id == community.id);
|
||||
if (index >= 0) {
|
||||
communities[index] = community;
|
||||
await saveCommunities(communities);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a community by ID
|
||||
Future<void> removeCommunity(String communityId) async {
|
||||
final communities = await loadCommunities();
|
||||
communities.removeWhere((c) => c.id == communityId);
|
||||
await saveCommunities(communities);
|
||||
}
|
||||
|
||||
/// Get a community by ID
|
||||
Future<Community?> getCommunity(String communityId) async {
|
||||
final communities = await loadCommunities();
|
||||
try {
|
||||
return communities.firstWhere((c) => c.id == communityId);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a community with the same secret already exists
|
||||
/// (to prevent duplicate imports from QR scanning)
|
||||
Future<Community?> findByCommunityId(String cid) async {
|
||||
final communities = await loadCommunities();
|
||||
try {
|
||||
return communities.firstWhere((c) => c.communityId == cid);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a hashtag channel to a community
|
||||
Future<void> addHashtagChannel(
|
||||
String communityId,
|
||||
String hashtag,
|
||||
) async {
|
||||
final community = await getCommunity(communityId);
|
||||
if (community != null) {
|
||||
final updated = community.addHashtagChannel(hashtag);
|
||||
await updateCommunity(updated);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a hashtag channel from a community
|
||||
Future<void> removeHashtagChannel(
|
||||
String communityId,
|
||||
String hashtag,
|
||||
) async {
|
||||
final community = await getCommunity(communityId);
|
||||
if (community != null) {
|
||||
final updated = community.removeHashtagChannel(hashtag);
|
||||
await updateCommunity(updated);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,233 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
/// A reusable QR code display widget for sharing data.
|
||||
///
|
||||
/// Features:
|
||||
/// - Configurable size and colors
|
||||
/// - Optional logo/icon in center
|
||||
/// - Automatic theming (light/dark mode aware)
|
||||
/// - Title and instructions
|
||||
class QrCodeDisplay extends StatelessWidget {
|
||||
/// The data to encode in the QR code
|
||||
final String data;
|
||||
|
||||
/// Size of the QR code (width and height)
|
||||
final double size;
|
||||
|
||||
/// Optional widget to display in the center (e.g., app logo)
|
||||
final Widget? embeddedImage;
|
||||
|
||||
/// Size of the embedded image (if provided)
|
||||
final double embeddedImageSize;
|
||||
|
||||
/// Title displayed above the QR code
|
||||
final String? title;
|
||||
|
||||
/// Instructions displayed below the QR code
|
||||
final String? instructions;
|
||||
|
||||
/// Background color of the QR code (defaults to white)
|
||||
final Color? backgroundColor;
|
||||
|
||||
/// Foreground color of the QR code modules (defaults to black)
|
||||
final Color? foregroundColor;
|
||||
|
||||
/// Padding around the QR code
|
||||
final EdgeInsets padding;
|
||||
|
||||
/// Error correction level
|
||||
final int errorCorrectionLevel;
|
||||
|
||||
const QrCodeDisplay({
|
||||
super.key,
|
||||
required this.data,
|
||||
this.size = 200,
|
||||
this.embeddedImage,
|
||||
this.embeddedImageSize = 50,
|
||||
this.title,
|
||||
this.instructions,
|
||||
this.backgroundColor,
|
||||
this.foregroundColor,
|
||||
this.padding = const EdgeInsets.all(16),
|
||||
this.errorCorrectionLevel = QrErrorCorrectLevel.M,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isDark = theme.brightness == Brightness.dark;
|
||||
|
||||
// Default colors based on theme
|
||||
final bgColor = backgroundColor ?? Colors.white;
|
||||
final fgColor = foregroundColor ?? Colors.black;
|
||||
|
||||
return Padding(
|
||||
padding: padding,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (title != null) ...[
|
||||
Text(
|
||||
title!,
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// QR code container with rounded corners
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: isDark
|
||||
? null
|
||||
: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.1),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: embeddedImage != null
|
||||
? _buildQrWithEmbeddedImage(fgColor, bgColor)
|
||||
: _buildSimpleQr(fgColor, bgColor),
|
||||
),
|
||||
|
||||
if (instructions != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
instructions!,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSimpleQr(Color fgColor, Color bgColor) {
|
||||
return QrImageView(
|
||||
data: data,
|
||||
version: QrVersions.auto,
|
||||
size: size,
|
||||
backgroundColor: bgColor,
|
||||
errorCorrectionLevel: errorCorrectionLevel,
|
||||
eyeStyle: QrEyeStyle(
|
||||
eyeShape: QrEyeShape.square,
|
||||
color: fgColor,
|
||||
),
|
||||
dataModuleStyle: QrDataModuleStyle(
|
||||
dataModuleShape: QrDataModuleShape.square,
|
||||
color: fgColor,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQrWithEmbeddedImage(Color fgColor, Color bgColor) {
|
||||
return Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
QrImageView(
|
||||
data: data,
|
||||
version: QrVersions.auto,
|
||||
size: size,
|
||||
backgroundColor: bgColor,
|
||||
// Use higher error correction when embedding image
|
||||
errorCorrectionLevel: QrErrorCorrectLevel.H,
|
||||
eyeStyle: QrEyeStyle(
|
||||
eyeShape: QrEyeShape.square,
|
||||
color: fgColor,
|
||||
),
|
||||
dataModuleStyle: QrDataModuleStyle(
|
||||
dataModuleShape: QrDataModuleShape.square,
|
||||
color: fgColor,
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: embeddedImageSize,
|
||||
height: embeddedImageSize,
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: embeddedImage,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialog to display a QR code for sharing
|
||||
class QrCodeShareDialog extends StatelessWidget {
|
||||
final String data;
|
||||
final String? title;
|
||||
final String? instructions;
|
||||
final Widget? embeddedImage;
|
||||
|
||||
const QrCodeShareDialog({
|
||||
super.key,
|
||||
required this.data,
|
||||
this.title,
|
||||
this.instructions,
|
||||
this.embeddedImage,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Dialog(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
QrCodeDisplay(
|
||||
data: data,
|
||||
size: 250,
|
||||
title: title,
|
||||
instructions: instructions,
|
||||
embeddedImage: embeddedImage,
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Done'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Show the dialog
|
||||
static Future<void> show({
|
||||
required BuildContext context,
|
||||
required String data,
|
||||
String? title,
|
||||
String? instructions,
|
||||
Widget? embeddedImage,
|
||||
}) {
|
||||
return showDialog(
|
||||
context: context,
|
||||
builder: (context) => QrCodeShareDialog(
|
||||
data: data,
|
||||
title: title,
|
||||
instructions: instructions,
|
||||
embeddedImage: embeddedImage,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,391 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
/// A reusable QR code scanner widget that can be embedded anywhere.
|
||||
///
|
||||
/// Features:
|
||||
/// - Configurable scan window overlay
|
||||
/// - Flash toggle button
|
||||
/// - Camera switch button (front/back)
|
||||
/// - Customizable callbacks for scan results
|
||||
/// - Optional validation function for QR data
|
||||
/// - Automatic pause when not visible
|
||||
/// - Debouncing to prevent duplicate scans
|
||||
class QrScannerWidget extends StatefulWidget {
|
||||
/// Called when a valid QR code is scanned
|
||||
final void Function(String data) onScanned;
|
||||
|
||||
/// Optional validator - return true if the QR data is valid
|
||||
final bool Function(String data)? validator;
|
||||
|
||||
/// Optional error callback when validation fails
|
||||
final void Function(String data)? onValidationFailed;
|
||||
|
||||
/// Whether to show the flash toggle button
|
||||
final bool showFlashButton;
|
||||
|
||||
/// Whether to show the camera switch button
|
||||
final bool showCameraSwitchButton;
|
||||
|
||||
/// Custom overlay widget (defaults to scan window frame)
|
||||
final Widget? overlay;
|
||||
|
||||
/// Instructions text shown below the scan window
|
||||
final String? instructions;
|
||||
|
||||
/// Whether to continue scanning after first successful scan
|
||||
final bool continuousScanning;
|
||||
|
||||
/// Debounce duration to prevent duplicate scans
|
||||
final Duration debounceDuration;
|
||||
|
||||
const QrScannerWidget({
|
||||
super.key,
|
||||
required this.onScanned,
|
||||
this.validator,
|
||||
this.onValidationFailed,
|
||||
this.showFlashButton = true,
|
||||
this.showCameraSwitchButton = true,
|
||||
this.overlay,
|
||||
this.instructions,
|
||||
this.continuousScanning = false,
|
||||
this.debounceDuration = const Duration(milliseconds: 500),
|
||||
});
|
||||
|
||||
@override
|
||||
State<QrScannerWidget> createState() => _QrScannerWidgetState();
|
||||
}
|
||||
|
||||
class _QrScannerWidgetState extends State<QrScannerWidget>
|
||||
with WidgetsBindingObserver {
|
||||
late MobileScannerController _controller;
|
||||
bool _hasScanned = false;
|
||||
String? _lastScannedData;
|
||||
DateTime? _lastScanTime;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_controller = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// Handle app lifecycle changes - pause/resume scanner
|
||||
if (!_controller.value.hasCameraPermission) return;
|
||||
|
||||
switch (state) {
|
||||
case AppLifecycleState.resumed:
|
||||
_controller.start();
|
||||
break;
|
||||
case AppLifecycleState.inactive:
|
||||
case AppLifecycleState.paused:
|
||||
case AppLifecycleState.detached:
|
||||
case AppLifecycleState.hidden:
|
||||
_controller.stop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleDetection(BarcodeCapture capture) {
|
||||
// Prevent duplicate scans
|
||||
if (_hasScanned && !widget.continuousScanning) return;
|
||||
|
||||
final List<Barcode> barcodes = capture.barcodes;
|
||||
for (final barcode in barcodes) {
|
||||
final String? rawValue = barcode.rawValue;
|
||||
if (rawValue == null || rawValue.isEmpty) continue;
|
||||
|
||||
// Debounce - ignore if same data scanned too quickly
|
||||
final now = DateTime.now();
|
||||
if (_lastScannedData == rawValue &&
|
||||
_lastScanTime != null &&
|
||||
now.difference(_lastScanTime!) < widget.debounceDuration) {
|
||||
continue;
|
||||
}
|
||||
|
||||
_lastScannedData = rawValue;
|
||||
_lastScanTime = now;
|
||||
|
||||
// Validate if validator provided
|
||||
if (widget.validator != null && !widget.validator!(rawValue)) {
|
||||
widget.onValidationFailed?.call(rawValue);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mark as scanned to prevent duplicates
|
||||
if (!widget.continuousScanning) {
|
||||
setState(() {
|
||||
_hasScanned = true;
|
||||
});
|
||||
_controller.stop();
|
||||
}
|
||||
|
||||
// Notify callback
|
||||
widget.onScanned(rawValue);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset the scanner to allow scanning again
|
||||
void resetScanner() {
|
||||
setState(() {
|
||||
_hasScanned = false;
|
||||
_lastScannedData = null;
|
||||
_lastScanTime = null;
|
||||
});
|
||||
_controller.start();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
// Scanner view
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: _handleDetection,
|
||||
errorBuilder: (context, error, child) {
|
||||
return _buildErrorWidget(context, error);
|
||||
},
|
||||
),
|
||||
|
||||
// Overlay
|
||||
widget.overlay ?? _buildDefaultOverlay(context),
|
||||
|
||||
// Control buttons
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: _buildControls(context),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDefaultOverlay(BuildContext context) {
|
||||
return ColorFiltered(
|
||||
colorFilter: ColorFilter.mode(
|
||||
Colors.black.withValues(alpha: 0.5),
|
||||
BlendMode.srcOut,
|
||||
),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Container(
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.black,
|
||||
backgroundBlendMode: BlendMode.dstOut,
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
height: 250,
|
||||
width: 250,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red, // This color is used for cutout
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
if (widget.instructions != null) ...[
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
vertical: 12,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
widget.instructions!,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildControls(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (widget.showFlashButton)
|
||||
ValueListenableBuilder(
|
||||
valueListenable: _controller,
|
||||
builder: (context, state, child) {
|
||||
return IconButton.filled(
|
||||
onPressed: () => _controller.toggleTorch(),
|
||||
icon: Icon(
|
||||
state.torchState == TorchState.on
|
||||
? Icons.flash_on
|
||||
: Icons.flash_off,
|
||||
),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Colors.black54,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (widget.showFlashButton && widget.showCameraSwitchButton)
|
||||
const SizedBox(width: 24),
|
||||
if (widget.showCameraSwitchButton)
|
||||
IconButton.filled(
|
||||
onPressed: () => _controller.switchCamera(),
|
||||
icon: const Icon(Icons.cameraswitch),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Colors.black54,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildErrorWidget(BuildContext context, MobileScannerException error) {
|
||||
String message;
|
||||
IconData icon;
|
||||
|
||||
switch (error.errorCode) {
|
||||
case MobileScannerErrorCode.permissionDenied:
|
||||
message = 'Camera permission denied.\nPlease enable camera access in settings.';
|
||||
icon = Icons.no_photography;
|
||||
break;
|
||||
case MobileScannerErrorCode.unsupported:
|
||||
message = 'Camera not supported on this device.';
|
||||
icon = Icons.videocam_off;
|
||||
break;
|
||||
default:
|
||||
message = 'Failed to start camera.\n${error.errorDetails?.message ?? ''}';
|
||||
icon = Icons.error_outline;
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 64, color: Colors.grey),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
message,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.grey[600],
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A simpler scanner overlay with just corner brackets
|
||||
class ScannerCornerOverlay extends StatelessWidget {
|
||||
final double scanWindowSize;
|
||||
final Color borderColor;
|
||||
final double borderWidth;
|
||||
final double cornerLength;
|
||||
|
||||
const ScannerCornerOverlay({
|
||||
super.key,
|
||||
this.scanWindowSize = 250,
|
||||
this.borderColor = Colors.white,
|
||||
this.borderWidth = 3,
|
||||
this.cornerLength = 30,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: SizedBox(
|
||||
width: scanWindowSize,
|
||||
height: scanWindowSize,
|
||||
child: CustomPaint(
|
||||
painter: _CornerPainter(
|
||||
color: borderColor,
|
||||
strokeWidth: borderWidth,
|
||||
cornerLength: cornerLength,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CornerPainter extends CustomPainter {
|
||||
final Color color;
|
||||
final double strokeWidth;
|
||||
final double cornerLength;
|
||||
|
||||
_CornerPainter({
|
||||
required this.color,
|
||||
required this.strokeWidth,
|
||||
required this.cornerLength,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()
|
||||
..color = color
|
||||
..strokeWidth = strokeWidth
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeCap = StrokeCap.round;
|
||||
|
||||
final path = Path();
|
||||
|
||||
// Top-left corner
|
||||
path.moveTo(0, cornerLength);
|
||||
path.lineTo(0, 0);
|
||||
path.lineTo(cornerLength, 0);
|
||||
|
||||
// Top-right corner
|
||||
path.moveTo(size.width - cornerLength, 0);
|
||||
path.lineTo(size.width, 0);
|
||||
path.lineTo(size.width, cornerLength);
|
||||
|
||||
// Bottom-right corner
|
||||
path.moveTo(size.width, size.height - cornerLength);
|
||||
path.lineTo(size.width, size.height);
|
||||
path.lineTo(size.width - cornerLength, size.height);
|
||||
|
||||
// Bottom-left corner
|
||||
path.moveTo(cornerLength, size.height);
|
||||
path.lineTo(0, size.height);
|
||||
path.lineTo(0, size.height - cornerLength);
|
||||
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
|
||||
}
|
||||
@ -1 +1,121 @@
|
||||
{}
|
||||
{
|
||||
"bg": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"de": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"es": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"fr": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"it": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"nl": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"pl": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"pt": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"sk": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"sl": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"sv": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
],
|
||||
|
||||
"zh": [
|
||||
"community_regenerateSecret",
|
||||
"community_regenerateSecretConfirm",
|
||||
"community_regenerate",
|
||||
"community_secretRegenerated",
|
||||
"community_updateSecret",
|
||||
"community_secretUpdated",
|
||||
"community_scanToUpdateSecret"
|
||||
]
|
||||
}
|
||||
|
||||
Loading…
Reference in new issue