Merge pull request #1557 from cypherstack/julian/chore/small-fixes-cleanup
What changed, and why it matters
This is a large cleanup and refactoring pull request for the Stack Wallet app. It mainly centralizes how QR-code scanning results and camera-permission errors are handled, so individual screens no longer each contain their own permission-checking code. It also tidies up how trade details pick which wallet to display. There is no obvious new security vulnerability in the diff, but because the change touches many screens and the barcode scanner interface, a small bug in the shared scanner could affect many features. The commit is not described by the vendor as a security fix.
Review the centralized scanner implementation for correct handling of permission denial and null results across all call sites. Verify that the new firstOrNull trade-wallet lookup does not hide data-integrity issues. Because this is a broad refactor, regression-test QR scanning on both mobile and desktop, and confirm the new iOS dependency pins do not introduce supply-chain risk.
Security signals we found
Centralized error handling for camera permission and scanner errors
Removed duplicated permission-check code across many screens
Added mounted checks before using BuildContext after async scan
Changed trade wallet lookup from list access to firstOrNull to avoid out-of-bounds/empty-list issues
New iOS dependencies pinned in Package.resolved
Evidence from the diff
The commit refactors barcode_scanner_interface.dart and adds a ScanResult model with explicit failure reasons (cameraPermissionDenied, scannerError). It removes duplicated PlatformException try/catch blocks and checkCamPermDeniedMobileAndOpenAppSettings calls from ~15 UI screens, replacing them with a single scan() result and mounted guards. The scanner now returns failures instead of throwing, and camera-permission denial is handled centrally. Additional changes include using firstOrNull for wallet IDs in trade-detail lookups, removing an unused desktop QR dialog branch in slatepack_input_field.dart, and updating iOS Swift package pins (CocoaLumberjack, SVGKit, swift-log). Tests are updated/added for the new behavior.
Changed components
lib/utilities/barcode_scanner_interface.dartlib/models/scan_result.dartlib/widgets/qr_scanner.dartlib/widgets/desktop/qr_code_scanner_dialog.dartlib/pages/send_view/send_view.dartlib/pages/send_view/token_send_view.dartlib/pages/send_view/sol_token_send_view.dartlib/pages/send_view/frost_ms/recipient.dartlib/pages/buy_view/buy_form.dartlib/pages/exchange_view/exchange_step_views/step_2_view.dartlib/pages/exchange_view/exchange_view.dartlib/pages/address_book_views/subviews/new_contact_address_entry_form.dartlib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dartlib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dartlib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dartlib/pages/slatepack/slatepack_input_field.dartlib/pages/namecoin_names/sub_widgets/transfer_option_widget.dartlib/pages/paynym/add_new_paynym_follow_view.dartlib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dartlib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dartios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolvedInspect captured patch +865 / −1047
### ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,5 +1,14 @@
{
"pins" : [
+ {
+ "identity" : "cocoalumberjack",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/CocoaLumberjack/CocoaLumberjack.git",
+ "state" : {
+ "revision" : "c5f2ed4d219866117e135cf648180dc7b66739d3",
+ "version" : "3.9.1"
+ }
+ },
{
"identity" : "dkcamera",
"kind" : "remoteSourceControl",
@@ -36,6 +45,23 @@
"version" : "5.21.7"
}
},
+ {
+ "identity" : "svgkit",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/SVGKit/SVGKit.git",
+ "state" : {
+ "revision" : "6002a0ff6b2d4405805395959b92b38aa24662cb"
+ }
+ },
+ {
+ "identity" : "swift-log",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-log",
+ "state" : {
+ "revision" : "e3da04078777e6a1b72ce19981fbd6539b0847d8",
+ "version" : "1.17.0"
+ }
+ },
{
"identity" : "swiftygif",
"kind" : "remoteSourceControl",
### ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,5 +1,14 @@
{
"pins" : [
+ {
+ "identity" : "cocoalumberjack",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/CocoaLumberjack/CocoaLumberjack.git",
+ "state" : {
+ "revision" : "c5f2ed4d219866117e135cf648180dc7b66739d3",
+ "version" : "3.9.1"
+ }
+ },
{
"identity" : "dkcamera",
"kind" : "remoteSourceControl",
@@ -36,6 +45,23 @@
"version" : "5.21.7"
}
},
+ {
+ "identity" : "svgkit",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/SVGKit/SVGKit.git",
+ "state" : {
+ "revision" : "6002a0ff6b2d4405805395959b92b38aa24662cb"
+ }
+ },
+ {
+ "identity" : "swift-log",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-log",
+ "state" : {
+ "revision" : "e3da04078777e6a1b72ce19981fbd6539b0847d8",
+ "version" : "1.17.0"
+ }
+ },
{
"identity" : "swiftygif",
"kind" : "remoteSourceControl",
### lib/models/scan_result.dart
@@ -0,0 +1,13 @@
+enum ScanFailure { cameraPermissionDenied, scannerError }
+
+class ScanResult {
+ const ScanResult({required this.rawContent}) : failure = null;
+
+ const ScanResult.failed(ScanFailure reason)
+ : failure = reason,
+ rawContent = null;
+
+ /// Null when the user closed the scanner or the scan failed.
+ final String? rawContent;
+ final ScanFailure? failure;
+}
### lib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dart
@@ -13,7 +13,6 @@ import '../../../../providers/global/secure_store_provider.dart';
import '../../../../providers/providers.dart';
import '../../../../themes/stack_colors.dart';
import '../../../../utilities/assets.dart';
-import '../../../../utilities/barcode_scanner_interface.dart';
import '../../../../utilities/constants.dart';
import '../../../../utilities/logger.dart';
import '../../../../utilities/show_loading.dart';
@@ -204,45 +203,23 @@ class _RestoreFrostMsWalletViewState
}
Future<void> scanQr() async {
- try {
- if (Platform.isAndroid || Platform.isIOS) {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (Platform.isAndroid || Platform.isIOS) {
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
}
+ }
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
- // TODO [prio=low]: Validate QR code data.
- configFieldController.text = qrResult.rawContent!;
+ // TODO [prio=low]: Validate QR code data.
+ configFieldController.text = qrResult.rawContent!;
- setState(() {
- _configEmpty = configFieldController.text.isEmpty;
- });
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code: ",
- error: e,
- stackTrace: s,
- );
- }
- }
+ setState(() {
+ _configEmpty = configFieldController.text.isEmpty;
+ });
}
@override
### lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart
@@ -32,7 +32,6 @@ import '../../../services/wallets.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/address_utils.dart';
import '../../../utilities/assets.dart';
-import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/clipboard_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/custom_text_selection_controls.dart';
@@ -41,8 +40,6 @@ import '../../../utilities/logger.dart';
import '../../../utilities/text_styles.dart';
import '../../../utilities/util.dart';
import '../../../wallets/crypto_currency/crypto_currency.dart';
-import '../../../wallets/crypto_currency/coins/ethereum.dart';
-import '../../../wallets/crypto_currency/coins/solana.dart';
import '../../../wallets/isar/models/wallet_info.dart';
import '../../../wallets/wallet/impl/epiccash_wallet.dart';
import '../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart';
@@ -637,43 +634,20 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
}
Future<void> scanMnemonicQr() async {
- try {
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
-
- final results = AddressUtils.decodeQRSeedData(qrResult.rawContent ?? "");
-
- if (results["mnemonic"] != null) {
- final list = (results["mnemonic"] as List)
- .map((value) => value as String)
- .toList(growable: false);
- if (list.isNotEmpty) {
- _clearAndPopulateMnemonic(list);
- Logging.instance.i("mnemonic populated");
- } else {
- Logging.instance.i("mnemonic failed to populate");
- }
- }
- } on PlatformException catch (e, s) {
- // likely failed to get camera permissions
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+
+ if (!mounted || qrResult.rawContent == null) return;
+ final results = AddressUtils.decodeQRSeedData(qrResult.rawContent!);
+
+ if (results["mnemonic"] != null) {
+ final list = (results["mnemonic"] as List)
+ .map((value) => value as String)
+ .toList(growable: false);
+ if (list.isNotEmpty) {
+ _clearAndPopulateMnemonic(list);
+ Logging.instance.i("mnemonic populated");
} else {
- Logging.instance.e(
- "Restore wallet qr scan failed: $e",
- error: e,
- stackTrace: s,
- );
+ Logging.instance.i("mnemonic failed to populate");
}
}
}
### lib/pages/address_book_views/subviews/new_contact_address_entry_form.dart
@@ -24,7 +24,6 @@ import '../../../themes/coin_icon_provider.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/address_utils.dart';
import '../../../utilities/assets.dart';
-import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/clipboard_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/logger.dart';
@@ -65,77 +64,36 @@ class _NewContactAddressEntryFormState
List<CryptoCurrency> coins = [];
void _onQrTapped() async {
- try {
- // ref
- // .read(shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = false;
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
- // Future<void>.delayed(
- // const Duration(seconds: 2),
- // () => ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true,
- // );
-
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
-
- if (paymentData != null) {
- addressController.text = paymentData.address;
- ref.read(addressEntryDataProvider(widget.id)).address =
- addressController.text.isEmpty ? null : addressController.text;
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
- addressLabelController.text =
- paymentData.label ?? addressLabelController.text;
- ref
- .read(addressEntryDataProvider(widget.id))
- .addressLabel = addressLabelController.text.isEmpty
- ? null
- : addressLabelController.text;
+ if (paymentData != null) {
+ addressController.text = paymentData.address;
+ ref.read(addressEntryDataProvider(widget.id)).address =
+ addressController.text.isEmpty ? null : addressController.text;
- // now check for non standard encoded basic address
- } else if (ref.read(addressEntryDataProvider(widget.id)).coin != null) {
- if (ref
- .read(addressEntryDataProvider(widget.id))
- .coin!
- .validateAddress(qrResult.rawContent!)) {
- addressController.text = qrResult.rawContent!;
- ref.read(addressEntryDataProvider(widget.id)).address =
- qrResult.rawContent;
- }
- }
- } on PlatformException catch (e, s) {
- // ref
- // .read(shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true;
+ addressLabelController.text =
+ paymentData.label ?? addressLabelController.text;
+ ref
+ .read(addressEntryDataProvider(widget.id))
+ .addressLabel = addressLabelController.text.isEmpty
+ ? null
+ : addressLabelController.text;
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions to scan address qr code: ",
- error: e,
- stackTrace: s,
- );
+ // now check for non standard encoded basic address
+ } else if (ref.read(addressEntryDataProvider(widget.id)).coin != null) {
+ if (ref
+ .read(addressEntryDataProvider(widget.id))
+ .coin!
+ .validateAddress(qrResult.rawContent!)) {
+ addressController.text = qrResult.rawContent!;
+ ref.read(addressEntryDataProvider(widget.id)).address =
+ qrResult.rawContent;
}
}
}
@@ -201,9 +159,9 @@ class _NewContactAddressEntryFormState
offset: const Offset(0, -10),
elevation: 0,
decoration: BoxDecoration(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
),
@@ -214,9 +172,8 @@ class _NewContactAddressEntryFormState
),
isExpanded: true,
value: ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.coin),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.coin),
),
onChanged: (value) {
if (value is CryptoCurrency) {
@@ -248,13 +205,12 @@ class _NewContactAddressEntryFormState
Text(
coin.prettyName,
style:
- STextStyles.desktopTextExtraExtraSmall(
- context,
- ).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textDark,
- ),
+ STextStyles.desktopTextExtraExtraSmall(context)
+ .copyWith(
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textDark,
+ ),
),
],
),
@@ -277,9 +233,9 @@ class _NewContactAddressEntryFormState
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: RawMaterialButton(
- splashColor: Theme.of(
- context,
- ).extension<StackColors>()!.highlight,
+ splashColor: Theme.of(context)
+ .extension<StackColors>()!
+ .highlight,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
@@ -301,9 +257,8 @@ class _NewContactAddressEntryFormState
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.coin),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.coin),
) ==
null
? Text(
@@ -317,9 +272,8 @@ class _NewContactAddressEntryFormState
ref.watch(
coinIconProvider(
ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.coin),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.coin),
)!,
),
),
@@ -331,9 +285,8 @@ class _NewContactAddressEntryFormState
Text(
ref
.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.coin),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.coin),
)!
.prettyName,
style: STextStyles.itemSubtitle12(context),
@@ -345,9 +298,9 @@ class _NewContactAddressEntryFormState
Assets.svg.chevronDown,
width: 8,
height: 4,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle2,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle2,
),
],
),
@@ -426,9 +379,8 @@ class _NewContactAddressEntryFormState
child: Row(
children: [
if (ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.address),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.address),
) !=
null)
TextFieldIconButton(
@@ -445,9 +397,8 @@ class _NewContactAddressEntryFormState
child: const XIcon(),
),
if (ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.address),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.address),
) ==
null)
TextFieldIconButton(
@@ -477,9 +428,8 @@ class _NewContactAddressEntryFormState
),
if (!Util.isDesktop &&
ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.address),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.address),
) ==
null)
TextFieldIconButton(
@@ -512,9 +462,8 @@ class _NewContactAddressEntryFormState
),
),
if (!ref.watch(
- addressEntryDataProvider(
- widget.id,
- ).select((value) => value.isValidAddress),
+ addressEntryDataProvider(widget.id)
+ .select((value) => value.isValidAddress),
) &&
addressController.text.isNotEmpty)
Row(
@@ -528,9 +477,9 @@ class _NewContactAddressEntryFormState
"Invalid address",
textAlign: TextAlign.left,
style: STextStyles.label(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textError,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textError,
),
),
],
### lib/pages/buy_view/buy_form.dart
@@ -34,7 +34,6 @@ import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_input_formatter.dart';
import '../../utilities/assets.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/clipboard_interface.dart';
import '../../utilities/constants.dart';
import '../../utilities/enums/derive_path_type_enum.dart';
@@ -702,59 +701,37 @@ class _BuyFormState extends ConsumerState<BuyForm> {
}
void _onQrTapped() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
- if (paymentData != null) {
- // auto fill address
- _address = paymentData.address;
- _receiveAddressController.text = _address!;
+ if (paymentData != null) {
+ // auto fill address
+ _address = paymentData.address;
+ _receiveAddressController.text = _address!;
- setState(() {
- _addressToggleFlag = _receiveAddressController.text.isNotEmpty;
- });
+ setState(() {
+ _addressToggleFlag = _receiveAddressController.text.isNotEmpty;
+ });
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.rawContent;
- _receiveAddressController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.rawContent;
+ _receiveAddressController.text = _address ?? "";
- setState(() {
- _addressToggleFlag = _receiveAddressController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.e(
- "Failed to get camera permissions while trying to scan qr code in $runtimeType: ",
- error: e,
- stackTrace: s,
- );
- }
+ setState(() {
+ _addressToggleFlag = _receiveAddressController.text.isNotEmpty;
+ });
}
}
### lib/pages/exchange_view/exchange_step_views/step_2_view.dart
@@ -17,7 +17,6 @@ import '../../../models/exchange/incomplete_exchange.dart';
import '../../../providers/providers.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/address_utils.dart';
-import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/clipboard_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/extra_id_currency_support.dart';
@@ -99,114 +98,66 @@ class _Step2ViewState extends ConsumerState<Step2View> {
}
void _onRefundQrTapped() async {
- try {
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
-
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
-
- if (paymentData != null) {
- // auto fill address
- _refundController.text = paymentData.address;
- model.refundAddress = _refundController.text;
- _setRefundMemo(paymentData.memo);
-
- setState(() {
- enableNext =
- _toController.text.isNotEmpty &&
- _refundController.text.isNotEmpty;
- });
- } else {
- _refundController.text = qrResult.rawContent!;
- model.refundAddress = _refundController.text;
-
- setState(() {
- enableNext =
- _toController.text.isNotEmpty &&
- _refundController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in $runtimeType: ",
- error: e,
- stackTrace: s,
- );
- }
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
+
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
+
+ if (paymentData != null) {
+ // auto fill address
+ _refundController.text = paymentData.address;
+ model.refundAddress = _refundController.text;
+ _setRefundMemo(paymentData.memo);
+
+ setState(() {
+ enableNext =
+ _toController.text.isNotEmpty && _refundController.text.isNotEmpty;
+ });
+ } else {
+ _refundController.text = qrResult.rawContent!;
+ model.refundAddress = _refundController.text;
+
+ setState(() {
+ enableNext =
+ _toController.text.isNotEmpty && _refundController.text.isNotEmpty;
+ });
}
}
void _onToQrTapped() async {
- try {
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
-
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
-
- if (paymentData != null) {
- // auto fill address
- _toController.text = paymentData.address;
- model.recipientAddress = _toController.text;
- _setRecipientMemo(paymentData.memo);
-
- setState(() {
- enableNext =
- _toController.text.isNotEmpty &&
- (_refundController.text.isNotEmpty ||
- !ref.read(efExchangeProvider).supportsRefundAddress);
- });
- } else {
- _toController.text = qrResult.rawContent!;
- model.recipientAddress = _toController.text;
-
- setState(() {
- enableNext =
- _toController.text.isNotEmpty &&
- (_refundController.text.isNotEmpty ||
- !ref.read(efExchangeProvider).supportsRefundAddress);
- });
- }
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in $runtimeType: ",
- error: e,
- stackTrace: s,
- );
- }
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
+
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
+
+ if (paymentData != null) {
+ // auto fill address
+ _toController.text = paymentData.address;
+ model.recipientAddress = _toController.text;
+ _setRecipientMemo(paymentData.memo);
+
+ setState(() {
+ enableNext =
+ _toController.text.isNotEmpty &&
+ (_refundController.text.isNotEmpty ||
+ !ref.read(efExchangeProvider).supportsRefundAddress);
+ });
+ } else {
+ _toController.text = qrResult.rawContent!;
+ model.recipientAddress = _toController.text;
+
+ setState(() {
+ enableNext =
+ _toController.text.isNotEmpty &&
+ (_refundController.text.isNotEmpty ||
+ !ref.read(efExchangeProvider).supportsRefundAddress);
+ });
}
}
### lib/pages/exchange_view/exchange_view.dart
@@ -171,35 +171,24 @@ class _ExchangeViewState extends ConsumerState<ExchangeView> {
onTap: () async {
final String tradeId = trades[index].tradeId;
- final lookup = ref
- .read(tradeSentFromStackLookupProvider)
- .all;
-
- //todo: check if print needed
- // debugPrint("ALL: $lookup");
-
final String? txid = ref
.read(tradeSentFromStackLookupProvider)
.getTxidForTradeId(tradeId);
- final List<String>? walletIds = ref
+ final String? walletId = ref
.read(tradeSentFromStackLookupProvider)
- .getWalletIdsForTradeId(tradeId);
+ .getWalletIdsForTradeId(tradeId)
+ ?.firstOrNull;
- if (txid != null &&
- walletIds != null &&
- walletIds.isNotEmpty) {
+ if (txid != null && walletId != null) {
final wallet = ref
.read(pWallets)
- .getWallet(walletIds.first);
+ .getWallet(walletId);
//todo: check if print needed
// debugPrint("name: ${manager.walletName}");
final tx = await MainDB.instance
- .getTradeTransaction(
- walletIds.first,
- txid,
- );
+ .getTradeTransaction(walletId, txid);
if (mounted) {
unawaited(
@@ -208,7 +197,7 @@ class _ExchangeViewState extends ConsumerState<ExchangeView> {
arguments: Tuple4(
tradeId,
tx,
- walletIds.first,
+ walletId,
wallet.info.name,
),
),
@@ -221,7 +210,7 @@ class _ExchangeViewState extends ConsumerState<ExchangeView> {
arguments: Tuple4(
tradeId,
null,
- walletIds?.first,
+ walletId,
null,
),
),
### lib/pages/namecoin_names/sub_widgets/transfer_option_widget.dart
@@ -9,7 +9,6 @@ import '../../../models/isar/models/blockchain_data/utxo.dart';
import '../../../providers/providers.dart';
import '../../../utilities/address_utils.dart';
import '../../../utilities/amount/amount.dart';
-import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/clipboard_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/logger.dart';
@@ -228,59 +227,35 @@ class _TransferOptionWidgetState extends ConsumerState<TransferOptionWidget> {
}
Future<void> _scanQr() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
- final coin = ref.read(pWalletCoin(walletId));
+ final coin = ref.read(pWalletCoin(walletId));
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
- if (paymentData != null &&
- paymentData.coin?.uriScheme == coin.uriScheme) {
- // auto fill address
- _address = paymentData.address.trim();
- _addressController.text = _address!;
+ if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) {
+ // auto fill address
+ _address = paymentData.address.trim();
+ _addressController.text = _address!;
- _setValidAddressProviders(_address);
+ _setValidAddressProviders(_address);
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.rawContent!.split("\n").first.trim();
- _addressController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.rawContent!.split("\n").first.trim();
+ _addressController.text = _address ?? "";
- _setValidAddressProviders(_address);
- }
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.e(
- "Failed to get camera permissions while trying to scan qr code in"
- " $runtimeType",
- error: e,
- stackTrace: s,
- );
- }
+ _setValidAddressProviders(_address);
}
}
### lib/pages/paynym/add_new_paynym_follow_view.dart
@@ -18,9 +18,7 @@ import '../../models/paynym/paynym_account.dart';
import '../../providers/global/paynym_api_provider.dart';
import '../../providers/providers.dart';
import '../../themes/stack_colors.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/constants.dart';
-import '../../utilities/logger.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
import '../../widgets/conditional_parent.dart';
@@ -121,8 +119,9 @@ class _AddNewPaynymFollowViewState
await Future<void>.delayed(const Duration(milliseconds: 75));
}
+ if (!mounted) return;
final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ if (!mounted || qrResult.rawContent == null) return;
final pCodeString = qrResult.rawContent!;
@@ -134,21 +133,6 @@ class _AddNewPaynymFollowViewState
offset: pCodeString.length,
);
});
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- }
} catch (_) {
// scan failed
}
@@ -260,9 +244,9 @@ class _AddNewPaynymFollowViewState
children: [
RoundedContainer(
padding: const EdgeInsets.all(0),
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
height: 56,
child: Center(
child: TextField(
@@ -417,9 +401,9 @@ class _AddNewPaynymFollowViewState
if (_didSearch && _searchResult == null)
RoundedWhiteContainer(
borderColor: isDesktop
- ? Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar
: null,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
@@ -437,9 +421,9 @@ class _AddNewPaynymFollowViewState
RoundedWhiteContainer(
padding: const EdgeInsets.all(0),
borderColor: isDesktop
- ? Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar
: null,
child: PaynymCard(
key: UniqueKey(),
### lib/pages/send_view/frost_ms/recipient.dart
@@ -8,10 +8,9 @@ import '../../../utilities/address_utils.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_field_relocalization.dart';
import '../../../utilities/amount/amount_formatter.dart';
-import '../../../utilities/amount/amount_parser.dart';
import '../../../utilities/amount/amount_input_formatter.dart';
+import '../../../utilities/amount/amount_parser.dart';
import '../../../utilities/amount/amount_unit.dart';
-import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/logger.dart';
import '../../../utilities/text_styles.dart';
@@ -217,41 +216,17 @@ class _RecipientState extends ConsumerState<Recipient> {
}
void _onQrTapped() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
- if (!mounted) return;
-
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
-
- if (qrResult.rawContent == null || !mounted) return;
-
- _applyAddressInput(qrResult.rawContent!.trim());
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.e(
- "Failed to get camera permissions while "
- "trying to scan qr code in SendView: $e\n$s",
- error: e,
- stackTrace: s,
- );
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
}
+ if (!mounted) return;
+
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+
+ if (qrResult.rawContent == null || !mounted) return;
+
+ _applyAddressInput(qrResult.rawContent!.trim());
}
@override
### lib/pages/send_view/send_view.dart
@@ -38,11 +38,10 @@ import '../../utilities/address_utils.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_formatter.dart';
-import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_input_formatter.dart';
+import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/assets.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/clipboard_interface.dart';
import '../../utilities/constants.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
@@ -74,8 +73,8 @@ import '../../widgets/icon_widgets/addressbook_icon.dart';
import '../../widgets/icon_widgets/clipboard_icon.dart';
import '../../widgets/icon_widgets/qrcode_icon.dart';
import '../../widgets/icon_widgets/x_icon.dart';
-import '../../widgets/slatepack_method_toggle.dart';
import '../../widgets/rounded_white_container.dart';
+import '../../widgets/slatepack_method_toggle.dart';
import '../../widgets/stack_dialog.dart';
import '../../widgets/stack_text_field.dart';
import '../../widgets/textfield_icon_button.dart';
@@ -480,77 +479,33 @@ class _SendViewState extends ConsumerState<SendView> with SendFeeForm {
}
Future<void> _scanQr() async {
- try {
- // ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = false;
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
- if (!mounted) return;
-
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
-
- // Future<void>.delayed(
- // const Duration(seconds: 2),
- // () => ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true,
- // );
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
+ if (!mounted) return;
- if (qrResult.rawContent == null || !mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- allowMultipleRecipients: _supportsMultiRecipient,
- );
+ if (qrResult.rawContent == null || !mounted) return;
- if (paymentData != null &&
- paymentData.coin?.uriScheme == coin.uriScheme) {
- _applyUri(paymentData);
- } else {
- _setOpReturnData(null);
- _address = qrResult.rawContent!.split("\n").first.trim();
- sendToController.text = _address ?? "";
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ allowMultipleRecipients: _supportsMultiRecipient,
+ );
- _setValidAddressProviders(_address);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- // ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true;
+ if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) {
+ _applyUri(paymentData);
+ } else {
+ _setOpReturnData(null);
+ _address = qrResult.rawContent!.split("\n").first.trim();
+ sendToController.text = _address ?? "";
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.e(
- "Failed to get camera permissions while trying to scan qr code in SendView: ",
- error: e,
- stackTrace: s,
- );
- }
+ _setValidAddressProviders(_address);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
}
}
### lib/pages/send_view/sol_token_send_view.dart
@@ -31,7 +31,6 @@ import '../../utilities/amount/amount_formatter.dart';
import '../../utilities/amount/amount_input_formatter.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/assets.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/clipboard_interface.dart';
import '../../utilities/constants.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
@@ -142,92 +141,70 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView>
}
void _onTokenSendViewScanQrButtonPressed() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
+ if (!mounted || qrResult.rawContent == null) return;
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
- if (paymentData != null) {
- // auto fill address
- _address = paymentData.address.trim();
- sendToController.text = _address!;
+ if (paymentData != null) {
+ // auto fill address
+ _address = paymentData.address.trim();
+ sendToController.text = _address!;
- // autofill notes field
- if (paymentData.message != null) {
- noteController.text = paymentData.message!;
- } else if (paymentData.label != null) {
- noteController.text = paymentData.label!;
- }
+ // autofill notes field
+ if (paymentData.message != null) {
+ noteController.text = paymentData.message!;
+ } else if (paymentData.label != null) {
+ noteController.text = paymentData.label!;
+ }
- // autofill amount field
- if (paymentData.amount != null) {
- final tokenWallet = ref.read(pCurrentSolanaTokenWallet);
- if (tokenWallet != null) {
- final amount = Amount.tryParseCanonicalAmount(
- paymentData.amount!,
- fractionDigits: tokenWallet.tokenDecimals,
- truncateOverprecision: true,
+ // autofill amount field
+ if (paymentData.amount != null) {
+ final tokenWallet = ref.read(pCurrentSolanaTokenWallet);
+ if (tokenWallet != null) {
+ final amount = Amount.tryParseCanonicalAmount(
+ paymentData.amount!,
+ fractionDigits: tokenWallet.tokenDecimals,
+ truncateOverprecision: true,
+ );
+ if (amount != null) {
+ cryptoAmountController.text = Amount.formatEditableDecimal(
+ amount.decimal,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
);
- if (amount != null) {
- cryptoAmountController.text = Amount.formatEditableDecimal(
- amount.decimal,
- locale: ref.read(localeServiceChangeNotifierProvider).locale,
- );
- _amountToSend = amount;
- } else {
- cryptoAmountController.clear();
- _amountToSend = null;
- _cachedAmountToSend = null;
- }
+ _amountToSend = amount;
+ } else {
+ cryptoAmountController.clear();
+ _amountToSend = null;
+ _cachedAmountToSend = null;
}
}
+ }
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.rawContent!.split("\n").first.trim();
- sendToController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.rawContent!.split("\n").first.trim();
+ sendToController.text = _address ?? "";
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in SolTokenSendView: ",
- error: e,
- stackTrace: s,
- );
- }
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
}
}
### lib/pages/send_view/token_send_view.dart
@@ -28,11 +28,10 @@ import '../../utilities/address_utils.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_formatter.dart';
-import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_input_formatter.dart';
+import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/assets.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/clipboard_interface.dart';
import '../../utilities/constants.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
@@ -135,108 +134,66 @@ class _TokenSendViewState extends ConsumerState<TokenSendView>
}
void _onTokenSendViewScanQrButtonPressed() async {
- try {
- // ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = false;
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- // Future<void>.delayed(
- // const Duration(seconds: 2),
- // () => ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true,
- // );
+ if (!mounted || qrResult.rawContent == null) return;
- if (qrResult.rawContent == null) return;
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult.rawContent!,
+ logging: Logging.instance,
+ );
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult.rawContent!,
- logging: Logging.instance,
- );
+ if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) {
+ // auto fill address
+ _address = paymentData.address.trim();
+ sendToController.text = _address!;
- if (paymentData != null &&
- paymentData.coin?.uriScheme == coin.uriScheme) {
- // auto fill address
- _address = paymentData.address.trim();
- sendToController.text = _address!;
-
- // autofill notes field
- if (paymentData.message != null) {
- noteController.text = paymentData.message!;
- } else if (paymentData.label != null) {
- noteController.text = paymentData.label!;
- }
+ // autofill notes field
+ if (paymentData.message != null) {
+ noteController.text = paymentData.message!;
+ } else if (paymentData.label != null) {
+ noteController.text = paymentData.label!;
+ }
- // autofill amount field
- if (paymentData.amount != null) {
- final amount = Amount.tryParseCanonicalAmount(
- paymentData.amount!,
- fractionDigits: tokenContract.decimals,
- truncateOverprecision: true,
- );
- if (amount != null) {
- cryptoAmountController.text = ref
- .read(pAmountFormatter(coin))
- .formatEditable(amount);
- _amountToSend = amount;
- } else {
- cryptoAmountController.clear();
- _amountToSend = null;
- _cachedAmountToSend = null;
- }
+ // autofill amount field
+ if (paymentData.amount != null) {
+ final amount = Amount.tryParseCanonicalAmount(
+ paymentData.amount!,
+ fractionDigits: tokenContract.decimals,
+ truncateOverprecision: true,
+ );
+ if (amount != null) {
+ cryptoAmountController.text = ref
+ .read(pAmountFormatter(coin))
+ .formatEditable(amount);
+ _amountToSend = amount;
+ } else {
+ cryptoAmountController.clear();
+ _amountToSend = null;
+ _cachedAmountToSend = null;
}
+ }
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.rawContent!.split("\n").first.trim();
- sendToController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.rawContent!.split("\n").first.trim();
+ sendToController.text = _address ?? "";
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- // ref
- // .read(
- // shouldShowLockscreenOnResumeStateProvider
- // .state)
- // .state = true;
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in SendView: ",
- error: e,
- stackTrace: s,
- );
- }
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
}
}
### lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart
@@ -23,7 +23,6 @@ import '../../../../providers/global/secure_store_provider.dart';
import '../../../../providers/providers.dart';
import '../../../../themes/stack_colors.dart';
import '../../../../utilities/assets.dart';
-import '../../../../utilities/barcode_scanner_interface.dart';
import '../../../../utilities/constants.dart';
import '../../../../utilities/flutter_secure_storage_interface.dart';
import '../../../../utilities/logger.dart';
@@ -345,21 +344,6 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
if (qrResult != null) {
await _processQrData(qrResult);
}
- } on PlatformException {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- }
} finally {
_scanLock = false;
}
### lib/pages/slatepack/slatepack_input_field.dart
@@ -12,15 +12,13 @@ import '../../notifications/show_flush_bar.dart';
import '../../providers/global/barcode_scanner_provider.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/assets.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/clipboard_interface.dart';
import '../../utilities/constants.dart';
import '../../utilities/exception_message.dart';
import '../../utilities/logger.dart';
import '../../utilities/slatepack_terms.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
-import '../../widgets/desktop/qr_code_scanner_dialog.dart';
import '../../widgets/icon_widgets/clipboard_icon.dart';
import '../../widgets/icon_widgets/qrcode_icon.dart';
import '../../widgets/icon_widgets/x_icon.dart';
@@ -106,49 +104,16 @@ class _SlatepackInputFieldState extends ConsumerState<SlatepackInputField> {
if (_busy) return;
_busy = true;
try {
- if (Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS) {
- if (_focusNode.hasFocus) {
- _focusNode.unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
- if (!mounted) return;
- final result = await ref.read(pBarcodeScanner).scan(context: context);
- final text = result.rawContent?.trim();
- if (text != null && text.isNotEmpty) {
- _set(text);
- }
- } else {
- final text = await showDialog<String>(
- context: context,
- builder: (context) => const QrCodeScannerDialog(),
- );
- if (text != null && text.trim().isNotEmpty) {
- _set(text.trim());
- }
+ if ((Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS) &&
+ _focusNode.hasFocus) {
+ _focusNode.unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
}
- } on PlatformException catch (e, s) {
- Logging.instance.w(
- "Camera scan failed while scanning a ${widget.terms.noun}",
- error: e,
- stackTrace: s,
- );
- if (Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- }
- } else {
- _showError(stripExceptionPrefixes(e));
+ if (!mounted) return;
+ final result = await ref.read(pBarcodeScanner).scan(context: context);
+ final text = result.rawContent?.trim();
+ if (text != null && text.isNotEmpty) {
+ _set(text);
}
} catch (e, s) {
Logging.instance.w(
### lib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart
@@ -333,9 +333,10 @@ class _DesktopTradeRowCardState extends ConsumerState<DesktopTradeRowCard> {
final String? txid = ref
.read(tradeSentFromStackLookupProvider)
.getTxidForTradeId(tradeId);
- final List<String>? walletIds = ref
+ final String? walletId = ref
.read(tradeSentFromStackLookupProvider)
- .getWalletIdsForTradeId(tradeId);
+ .getWalletIdsForTradeId(tradeId)
+ ?.firstOrNull;
final trade = ref.watch(
tradesServiceProvider.select((value) => value.get(tradeId)),
@@ -356,13 +357,12 @@ class _DesktopTradeRowCardState extends ConsumerState<DesktopTradeRowCard> {
),
),
onPressed: () async {
- if (txid != null && walletIds != null && walletIds.isNotEmpty) {
+ if (txid != null && walletId != null) {
//todo: check if print needed
// debugPrint("name: ${manager.walletName}");
await loadAndPresentDesktopTradeDetails(
- load: () =>
- MainDB.instance.getTradeTransaction(walletIds.first, txid),
+ load: () => MainDB.instance.getTradeTransaction(walletId, txid),
present: (tx) {
if (mounted) {
unawaited(
@@ -411,9 +411,9 @@ class _DesktopTradeRowCardState extends ConsumerState<DesktopTradeRowCard> {
tradeId: tradeId,
transactionIfSentFromStack: tx,
walletName: ref.read(
- pWalletName(walletIds.first),
+ pWalletName(walletId),
),
- walletId: walletIds.first,
+ walletId: walletId,
),
),
),
@@ -477,7 +477,7 @@ class _DesktopTradeRowCardState extends ConsumerState<DesktopTradeRowCard> {
tradeId: tradeId,
transactionIfSentFromStack: null,
walletName: null,
- walletId: walletIds?.first,
+ walletId: walletId,
),
),
),
### lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart
@@ -92,28 +92,20 @@ class _DesktopTradeHistoryState extends ConsumerState<DesktopTradeHistory> {
onTap: () async {
final String tradeId = trades[index].tradeId;
- final lookup = ref
- .read(tradeSentFromStackLookupProvider)
- .all;
-
- //todo: check if print needed
- // debugPrint("ALL: $lookup");
-
final String? txid = ref
.read(tradeSentFromStackLookupProvider)
.getTxidForTradeId(tradeId);
- final List<String>? walletIds = ref
+ final String? walletId = ref
.read(tradeSentFromStackLookupProvider)
- .getWalletIdsForTradeId(tradeId);
+ .getWalletIdsForTradeId(tradeId)
+ ?.firstOrNull;
- if (txid != null &&
- walletIds != null &&
- walletIds.isNotEmpty) {
+ if (txid != null && walletId != null) {
//todo: check if print needed
// debugPrint("name: ${manager.walletName}");
final tx = await MainDB.instance.getTradeTransaction(
- walletIds.first,
+ walletId,
txid,
);
@@ -165,9 +157,9 @@ class _DesktopTradeHistoryState extends ConsumerState<DesktopTradeHistory> {
tradeId: tradeId,
transactionIfSentFromStack: tx,
walletName: ref.read(
- pWalletName(walletIds.first),
+ pWalletName(walletId),
),
- walletId: walletIds.first,
+ walletId: walletId,
),
),
),
@@ -233,7 +225,7 @@ class _DesktopTradeHistoryState extends ConsumerState<DesktopTradeHistory> {
transactionIfSentFromStack:
null,
walletName: null,
- walletId: walletIds?.first,
+ walletId: walletId,
),
),
),
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dart
@@ -475,80 +475,70 @@ class _DesktopSolTokenSendState extends ConsumerState<DesktopSolTokenSend> {
}
Future<void> scanQr() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = (await ref.read(pBarcodeScanner).scan(context: context))
- .rawContent;
+ if (!mounted) return;
+ final qrResult = (await ref.read(pBarcodeScanner).scan(context: context))
+ .rawContent;
- if (qrResult == null) {
- return;
- }
+ if (!mounted || qrResult == null) {
+ return;
+ }
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult,
- logging: Logging.instance,
- );
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult,
+ logging: Logging.instance,
+ );
- if (paymentData != null &&
- paymentData.coin?.uriScheme == coin.uriScheme) {
- // auto fill address
- _address = paymentData.address.trim();
- sendToController.text = _address!;
-
- // autofill notes field
- if (paymentData.message != null) {
- _note = paymentData.message!;
- } else if (paymentData.label != null) {
- _note = paymentData.label!;
- }
+ if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) {
+ // auto fill address
+ _address = paymentData.address.trim();
+ sendToController.text = _address!;
- // autofill amount field
- if (paymentData.amount != null) {
- final amount = Amount.tryParseCanonicalAmount(
- paymentData.amount!,
- fractionDigits: ref.read(pCurrentSolanaTokenWallet)!.tokenDecimals,
- truncateOverprecision: true,
+ // autofill notes field
+ if (paymentData.message != null) {
+ _note = paymentData.message!;
+ } else if (paymentData.label != null) {
+ _note = paymentData.label!;
+ }
+
+ // autofill amount field
+ if (paymentData.amount != null) {
+ final amount = Amount.tryParseCanonicalAmount(
+ paymentData.amount!,
+ fractionDigits: ref.read(pCurrentSolanaTokenWallet)!.tokenDecimals,
+ truncateOverprecision: true,
+ );
+ if (amount != null) {
+ cryptoAmountController.text = Amount.formatEditableDecimal(
+ amount.decimal,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
);
- if (amount != null) {
- cryptoAmountController.text = Amount.formatEditableDecimal(
- amount.decimal,
- locale: ref.read(localeServiceChangeNotifierProvider).locale,
- );
- _amountToSend = amount;
- } else {
- cryptoAmountController.clear();
- _amountToSend = null;
- _cachedAmountToSend = null;
- }
+ _amountToSend = amount;
+ } else {
+ cryptoAmountController.clear();
+ _amountToSend = null;
+ _cachedAmountToSend = null;
}
+ }
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.split("\n").first.trim();
- sendToController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.split("\n").first.trim();
+ sendToController.text = _address ?? "";
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- // here we ignore the exception caused by not giving permission
- // to use the camera to scan a qr code
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in SendView: ",
- error: e,
- stackTrace: s,
- );
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
}
}
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart
@@ -454,84 +454,71 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
}
Future<void> scanQr() async {
- try {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
+ }
- final qrResult = (await ref.read(pBarcodeScanner).scan(context: context))
- .rawContent;
+ if (!mounted) return;
+ final qrResult = (await ref.read(pBarcodeScanner).scan(context: context))
+ .rawContent;
- if (qrResult == null) {
- return;
- }
+ if (!mounted || qrResult == null) {
+ return;
+ }
- final paymentData = AddressUtils.parsePaymentUri(
- qrResult,
- logging: Logging.instance,
- );
+ final paymentData = AddressUtils.parsePaymentUri(
+ qrResult,
+ logging: Logging.instance,
+ );
- if (paymentData != null &&
- paymentData.coin?.uriScheme == coin.uriScheme) {
- // auto fill address
- _address = paymentData.address.trim();
- sendToController.text = _address!;
-
- // autofill notes field
- if (paymentData.message != null) {
- _note = paymentData.message!;
- } else if (paymentData.label != null) {
- _note = paymentData.label!;
- }
+ if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) {
+ // auto fill address
+ _address = paymentData.address.trim();
+ sendToController.text = _address!;
- // autofill amount field
- if (paymentData.amount != null) {
- final amount = Amount.tryParseCanonicalAmount(
- paymentData.amount!,
- fractionDigits: ref
- .read(pCurrentTokenWallet)!
- .tokenContract
- .decimals,
- truncateOverprecision: true,
- );
- if (amount != null) {
- cryptoAmountController.text = ref
- .read(pAmountFormatter(coin))
- .formatEditable(amount);
- _amountToSend = amount;
- _syncFeeAmount(amount);
- } else {
- cryptoAmountController.clear();
- _amountToSend = null;
- _cachedAmountToSend = null;
- _syncFeeAmount(null);
- }
+ // autofill notes field
+ if (paymentData.message != null) {
+ _note = paymentData.message!;
+ } else if (paymentData.label != null) {
+ _note = paymentData.label!;
+ }
+
+ // autofill amount field
+ if (paymentData.amount != null) {
+ final amount = Amount.tryParseCanonicalAmount(
+ paymentData.amount!,
+ fractionDigits: ref.read(pCurrentTokenWallet)!.tokenContract.decimals,
+ truncateOverprecision: true,
+ );
+ if (amount != null) {
+ cryptoAmountController.text = ref
+ .read(pAmountFormatter(coin))
+ .formatEditable(amount);
+ _amountToSend = amount;
+ _syncFeeAmount(amount);
+ } else {
+ cryptoAmountController.clear();
+ _amountToSend = null;
+ _cachedAmountToSend = null;
+ _syncFeeAmount(null);
}
+ }
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
- // now check for non standard encoded basic address
- } else {
- _address = qrResult.split("\n").first.trim();
- sendToController.text = _address ?? "";
+ // now check for non standard encoded basic address
+ } else {
+ _address = qrResult.split("\n").first.trim();
+ sendToController.text = _address ?? "";
- _updatePreviewButtonState(_address, _amountToSend);
- setState(() {
- _addressToggleFlag = sendToController.text.isNotEmpty;
- });
- }
- } on PlatformException catch (e, s) {
- // here we ignore the exception caused by not giving permission
- // to use the camera to scan a qr code
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code in SendView: ",
- error: e,
- stackTrace: s,
- );
+ _updatePreviewButtonState(_address, _amountToSend);
+ setState(() {
+ _addressToggleFlag = sendToController.text.isNotEmpty;
+ });
}
}
### lib/utilities/barcode_scanner_interface.dart
@@ -8,24 +8,20 @@
*
*/
-import 'dart:io';
-
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
+import '../models/scan_result.dart';
import '../widgets/desktop/primary_button.dart';
import '../widgets/desktop/qr_code_scanner_dialog.dart';
import '../widgets/desktop/secondary_button.dart';
import '../widgets/qr_scanner.dart';
import '../widgets/stack_dialog.dart';
import 'logger.dart';
+import 'route_presentation.dart';
-class ScanResult {
- final String? rawContent;
-
- ScanResult({required this.rawContent});
-}
+export '../models/scan_result.dart';
abstract class BarcodeScannerInterface {
Future<ScanResult> scan({required BuildContext context});
@@ -42,75 +38,74 @@ class BarcodeScannerWrapper implements BarcodeScannerInterface {
@override
Future<ScanResult> scan({required BuildContext context}) async {
try {
- final data = await showDialog<String>(
+ final result = await showDialog<ScanResult>(
context: context,
builder: (context) => scanner,
);
- if (data == null) {
+ final data = result?.rawContent;
+ if (result?.failure == ScanFailure.cameraPermissionDenied) {
+ if (context.mounted) await _handleCameraPermissionDenied(context);
+ } else if (data == null) {
Logging.instance.d("Qr scanning cancelled");
} else if (kDebugMode) {
Logging.instance.d("qrResult content: $data");
}
- return ScanResult(rawContent: data);
+ return result ?? const ScanResult(rawContent: null);
} catch (e, s) {
- Logging.instance.e(
- "Error opening QR code scanner dialog",
- error: e,
- stackTrace: s,
- );
- return ScanResult(rawContent: null);
+ Logging.instance.e("QR code scan failed", error: e, stackTrace: s);
+ return const ScanResult.failed(ScanFailure.scannerError);
}
}
}
-/// Check if cam perms permanently denied on mobile and open app settings
-Future<void> checkCamPermDeniedMobileAndOpenAppSettings(
- BuildContext context, {
- required Logging logging,
-}) async {
- if (Platform.isAndroid || Platform.isIOS) {
- final status = await Permission.camera.status;
- final androidShow =
- Platform.isAndroid && status == PermissionStatus.permanentlyDenied;
- final iosShow = Platform.isIOS && status == PermissionStatus.denied;
+Future<void> _handleCameraPermissionDenied(BuildContext context) async {
+ // After a denied request Android can prompt again while a rationale is
+ // available. On iOS the user must grant camera access in Settings.
+ if (defaultTargetPlatform == TargetPlatform.android &&
+ await Permission.camera.shouldShowRequestRationale) {
+ return;
+ }
+ if (!context.mounted ||
+ !isHostRouteCurrent(
+ context,
+ Navigator.of(context, rootNavigator: true),
+ )) {
+ return;
+ }
+ final trySettings = await showDialog<bool>(
+ context: context,
+ builder: (context) => StackDialog(
+ title: "Camera permissions required",
+ message: "Open settings?",
+ leftButton: SecondaryButton(
+ label: "Cancel",
+ onPressed: Navigator.of(context).pop,
+ ),
+ rightButton: PrimaryButton(
+ label: "Continue",
+ onPressed: () => Navigator.of(context).pop(true),
+ ),
+ ),
+ );
- if ((iosShow || androidShow) && context.mounted) {
- final trySettings = await showDialog<bool>(
- context: context,
- builder: (context) => StackDialog(
- title: "Camera permissions required",
- message: "Open settings?",
- leftButton: SecondaryButton(
- label: "Cancel",
- onPressed: Navigator.of(context).pop,
- ),
- rightButton: PrimaryButton(
- label: "Continue",
- onPressed: () => Navigator.of(context).pop(true),
+ if (trySettings == true) {
+ final success = await openAppSettings();
+ if (!success) {
+ Logging.instance.e("Failed to open app settings");
+ if (context.mounted) {
+ await showDialog<bool>(
+ context: context,
+ builder: (context) => StackDialog(
+ title: "Could not open app settings",
+ message: "You will need manually go find your app settings",
+ rightButton: PrimaryButton(
+ label: "Ok",
+ onPressed: Navigator.of(context).pop,
+ ),
),
- ),
- );
-
- if (trySettings == true) {
- final success = await openAppSettings();
- if (!success) {
- logging.e("Failed to open app settings");
- if (context.mounted) {
- await showDialog<bool>(
- context: context,
- builder: (context) => StackDialog(
- title: "Could not open app settings",
- message: "You will need manually go find your app settings",
- rightButton: PrimaryButton(
- label: "Ok",
- onPressed: Navigator.of(context).pop,
- ),
- ),
- );
- }
- }
+ );
}
}
}
### lib/widgets/desktop/qr_code_scanner_dialog.dart
@@ -15,6 +15,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image/image.dart' as img;
+import '../../models/scan_result.dart';
import '../../notifications/show_flush_bar.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/assets.dart';
@@ -487,7 +488,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
await _stopCamera();
if (mounted) {
- Navigator.of(context).pop(scanResult);
+ Navigator.of(context).pop(ScanResult(rawContent: scanResult));
}
break;
} else {
@@ -662,7 +663,8 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
final String? scanResult = await _scanImage(image);
if (context.mounted) {
if (scanResult != null && scanResult.isNotEmpty) {
- Navigator.of(context).pop(scanResult);
+ Navigator.of(context)
+ .pop(ScanResult(rawContent: scanResult));
} else {
await showFloatingFlushBar(
type: FlushBarType.info,
### lib/widgets/qr_scanner.dart
@@ -4,8 +4,8 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
+import '../models/scan_result.dart';
import '../themes/stack_colors.dart';
-import '../utilities/if_not_already.dart';
import '../utilities/text_styles.dart';
import 'background.dart';
import 'custom_buttons/app_bar_icon_button.dart';
@@ -24,18 +24,17 @@ class _QrScannerState extends State<QrScanner> {
StreamSubscription<Barcode>? sub;
- late final Future<void> Function(String?) _onScanned;
-
- @override
- void initState() {
- super.initState();
-
- _onScanned = IfNotAlreadyAsync<String>.withArgs((data) async {
- await sub?.cancel();
- if (mounted) {
- Navigator.of(context).pop(data);
- }
- }).execute;
+ void _finish(ScanResult result) {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route == null || !route.isActive) return;
+ final navigator = Navigator.of(context);
+ if (route.isCurrent) {
+ navigator.pop(result);
+ } else {
+ // A newer route (such as the app lock) can cover the camera.
+ navigator.removeRoute(route, result);
+ }
}
// In order to get hot reload to work we need to pause the camera if the platform
@@ -62,19 +61,26 @@ class _QrScannerState extends State<QrScanner> {
child: Scaffold(
backgroundColor: Theme.of(context).extension<StackColors>()!.background,
appBar: AppBar(
- backgroundColor: Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar,
leading: const AppBarBackButton(),
title: Text("Scan QR code", style: STextStyles.navBarTitle(context)),
),
body: QRView(
key: qrKey,
+ onPermissionSet: (_, granted) {
+ if (!granted) {
+ _finish(
+ const ScanResult.failed(ScanFailure.cameraPermissionDenied),
+ );
+ }
+ },
onQRViewCreated: (QRViewController p1) {
sub?.cancel();
controller = p1;
sub = controller!.scannedDataStream.listen((data) {
- _onScanned(data.code);
+ _finish(ScanResult(rawContent: data.code));
});
},
),
### lib/widgets/textfields/frost_step_field.dart
@@ -6,9 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/providers.dart';
import '../../themes/stack_colors.dart';
-import '../../utilities/barcode_scanner_interface.dart';
import '../../utilities/constants.dart';
-import '../../utilities/logger.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
import '../conditional_parent.dart';
@@ -71,43 +69,21 @@ class _FrostStepFieldState extends ConsumerState<FrostStepField> {
}
Future<void> scanQr() async {
- try {
- if (Platform.isAndroid || Platform.isIOS) {
- if (FocusScope.of(context).hasFocus) {
- FocusScope.of(context).unfocus();
- await Future<void>.delayed(const Duration(milliseconds: 75));
- }
- }
-
- final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
- if (qrResult.rawContent == null) return;
-
- // TODO [prio=low]: Validate QR code data.
- widget.controller.text = qrResult.rawContent!;
-
- _changed(widget.controller.text);
- } on PlatformException catch (e, s) {
- if (mounted) {
- try {
- await checkCamPermDeniedMobileAndOpenAppSettings(
- context,
- logging: Logging.instance,
- );
- } catch (e, s) {
- Logging.instance.e(
- "Failed to check cam permissions",
- error: e,
- stackTrace: s,
- );
- }
- } else {
- Logging.instance.w(
- "Failed to get camera permissions while trying to scan qr code: ",
- error: e,
- stackTrace: s,
- );
+ if (Platform.isAndroid || Platform.isIOS) {
+ if (FocusScope.of(context).hasFocus) {
+ FocusScope.of(context).unfocus();
+ await Future<void>.delayed(const Duration(milliseconds: 75));
}
}
+
+ if (!mounted) return;
+ final qrResult = await ref.read(pBarcodeScanner).scan(context: context);
+ if (!mounted || qrResult.rawContent == null) return;
+
+ // TODO [prio=low]: Validate QR code data.
+ widget.controller.text = qrResult.rawContent!;
+
+ _changed(widget.controller.text);
}
@override
### pubspec.lock
@@ -1046,8 +1046,8 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: "d4852f3ebaaef20d71a8954098634af8e25c3b50"
- resolved-ref: "d4852f3ebaaef20d71a8954098634af8e25c3b50"
+ ref: d4852f3ebaaef20d71a8954098634af8e25c3b50
+ resolved-ref: d4852f3ebaaef20d71a8954098634af8e25c3b50
url: "https://github.com/cypherstack/flutter_libmwc.git"
source: git
version: "0.1.0"
### test/pages/exchange_view/trade_details_view_test.dart
@@ -17,6 +17,8 @@ import 'package:stackwallet/models/isar/models/contact_entry.dart';
import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart';
import 'package:stackwallet/models/isar/models/transaction_note.dart';
import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/models/trade_wallet_lookup.dart';
+import 'package:stackwallet/pages/exchange_view/exchange_view.dart';
import 'package:stackwallet/pages/exchange_view/trade_details_view.dart';
import 'package:stackwallet/pages/home_view/home_view.dart';
import 'package:stackwallet/pages/pinpad_views/lock_screen_view.dart';
@@ -27,10 +29,13 @@ import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/boost_tran
import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart';
import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list_item.dart';
import 'package:stackwallet/pages/wallet_view/wallet_view.dart';
+import 'package:stackwallet/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart';
+import 'package:stackwallet/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart';
import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart';
import 'package:stackwallet/providers/db/main_db_provider.dart';
import 'package:stackwallet/providers/desktop/storage_crypto_handler_provider.dart';
import 'package:stackwallet/providers/exchange/trade_note_service_provider.dart';
+import 'package:stackwallet/providers/exchange/trade_sent_from_stack_lookup_provider.dart';
import 'package:stackwallet/providers/global/address_book_service_provider.dart';
import 'package:stackwallet/providers/global/locale_provider.dart';
import 'package:stackwallet/providers/global/prefs_provider.dart';
@@ -42,6 +47,7 @@ import 'package:stackwallet/services/address_book_service.dart';
import 'package:stackwallet/services/exchange/exolix/exolix_exchange.dart';
import 'package:stackwallet/services/locale_service.dart';
import 'package:stackwallet/services/trade_notes_service.dart';
+import 'package:stackwallet/services/trade_sent_from_stack_service.dart';
import 'package:stackwallet/services/trade_service.dart';
import 'package:stackwallet/services/wallets.dart';
import 'package:stackwallet/themes/coin_image_provider.dart';
@@ -71,7 +77,7 @@ import '../send_view/support/send_view_harness.dart' show loadButtonFont;
class _ThemeService extends Mock implements ThemeService {}
class _Prefs extends Mock implements Prefs {
- _Prefs(this.unit);
+ _Prefs(this.unit, {this.externalCalls = false});
final AmountUnit unit;
int _lastUnlocked = 0;
@@ -80,7 +86,7 @@ class _Prefs extends Mock implements Prefs {
bool get isInitialized => true;
@override
- bool get externalCalls => false;
+ final bool externalCalls;
@override
String get currency => 'USD';
@@ -193,6 +199,25 @@ class _Trades extends TradesService {
@override
List<Trade> get trades => _trades;
+
+ @override
+ Trade? get(String tradeId) =>
+ trades.where((t) => t.tradeId == tradeId).firstOrNull;
+}
+
+class _TradeLookup extends TradeSentFromStackService {
+ _TradeLookup(Trade trade)
+ : all = [
+ TradeWalletLookup(
+ uuid: 'lookup',
+ tradeId: trade.tradeId,
+ txid: 'pay-in',
+ walletIds: [],
+ ),
+ ];
+
+ @override
+ final List<TradeWalletLookup> all;
}
class _Notes extends TradeNotesService {
@@ -313,6 +338,7 @@ Future<void> _pump(
RouteFactory? onGenerateRoute,
Size surfaceSize = const Size(1400, 3000),
Wallets? wallets,
+ bool externalCalls = false,
List<Override> overrides = const [],
}) async {
tester.view.physicalSize = surfaceSize;
@@ -327,7 +353,9 @@ Future<void> _pump(
ProviderScope(
overrides: [
pThemeService.overrideWithValue(themeService),
- prefsChangeNotifierProvider.overrideWithValue(_Prefs(unit)),
+ prefsChangeNotifierProvider.overrideWithValue(
+ _Prefs(unit, externalCalls: externalCalls),
+ ),
localeServiceChangeNotifierProvider.overrideWithValue(_LocaleService()),
tradesServiceProvider.overrideWithValue(_Trades([trade])),
tradeNoteServiceProvider.overrideWithValue(_Notes()),
@@ -357,6 +385,44 @@ Future<void> _pump(
void main() {
setUpAll(loadButtonFont);
+ for (final (name, desktop, home) in [
+ ('mobile history', false, const ExchangeView()),
+ ('desktop history', true, const DesktopTradeHistory()),
+ ('desktop all trades', true, const DesktopTradeRowCard(tradeId: 'trade-1')),
+ ]) {
+ testWidgets('$name opens a trade after its last wallet is deleted', (
+ tester,
+ ) async {
+ _setLayoutPlatform(isDesktop: desktop);
+ _useSampleThemesDir();
+ final trade = _trade(payInCurrency: 'BTC').copyWith(status: 'Finished');
+ await _pump(
+ tester,
+ trade,
+ home: Scaffold(body: home),
+ externalCalls: true,
+ overrides: [
+ tradeSentFromStackLookupProvider.overrideWithValue(
+ _TradeLookup(trade),
+ ),
+ ],
+ );
+ final card = home is DesktopTradeRowCard
+ ? find.byType(RawMaterialButton)
+ : find.byType(TradeCard);
+ await tester.ensureVisible(card);
+ await tester.tap(card);
+ await tester.pumpAndSettle();
+ final details = tester.widget<TradeDetailsView>(
+ find.byType(TradeDetailsView),
+ );
+ expect(details.tradeId, trade.tradeId);
+ expect(details.walletId, isNull);
+ expect(details.transactionIfSentFromStack, isNull);
+ expect(find.text('View transaction'), findsNothing);
+ });
+ }
+
testWidgets('mobile token trade card opens its linked V2 transaction', (
tester,
) async {
### test/pages/slatepack/slatepack_input_field_test.dart
@@ -8,6 +8,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:platform/platform.dart' as platform;
import 'package:stackwallet/models/isar/stack_theme.dart';
import 'package:stackwallet/pages/slatepack/slatepack_input_field.dart';
+import 'package:stackwallet/providers/global/barcode_scanner_provider.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/themes/theme_providers.dart';
import 'package:stackwallet/utilities/clipboard_interface.dart';
@@ -16,6 +17,7 @@ import 'package:stackwallet/utilities/stack_file_system.dart';
import 'package:stackwallet/utilities/util.dart';
import '../../sample_data/theme_json.dart';
+import '../../utilities/fake_scanner.dart';
class _Clipboard extends Fake implements ClipboardInterface {
final response = Completer<ClipboardData?>();
@@ -81,6 +83,52 @@ void main() {
expect(tester.takeException(), isNull);
});
+ testWidgets(
+ 'desktop scan uses the shared scanner and cancel preserves the input',
+ (tester) async {
+ final previousPlatform = Util.layoutPlatform;
+ Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux');
+ addTearDown(() => Util.layoutPlatform = previousPlatform);
+ final controller = TextEditingController();
+ addTearDown(controller.dispose);
+ final changes = <String>[];
+ final scanner = FakeScanner();
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
+ pBarcodeScanner.overrideWithValue(scanner),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Scaffold(
+ body: SlatepackInputField(
+ controller: controller,
+ hint: 'Slatepack',
+ terms: SlatepackTerms.slatepack,
+ onChanged: changes.add,
+ ),
+ ),
+ ),
+ ),
+ );
+ final button = find.byKey(const Key('slatepackScanButton'));
+ await tester.tap(button);
+ await tester.pump();
+ expect(controller.text, isEmpty);
+ expect(changes, isEmpty);
+ scanner.rawContent = ' scanned slatepack ';
+ await tester.tap(button);
+ await tester.pump();
+ expect(scanner.scans, 2);
+ expect(controller.text, 'scanned slatepack');
+ expect(changes, ['scanned slatepack']);
+ },
+ );
+
testWidgets('paste completes after the input closes', (tester) async {
final previousThemes = StackFileSystem.themesDir;
StackFileSystem.themesDir = Directory('test/sample_data').absolute;
### test/utilities/barcode_scanner_interface_test.dart
@@ -1,11 +1,21 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_providers.dart';
import 'package:stackwallet/utilities/barcode_scanner_interface.dart';
import 'package:stackwallet/widgets/desktop/qr_code_scanner_dialog.dart';
import 'package:stackwallet/widgets/qr_scanner.dart';
+import '../sample_data/theme_json.dart';
+
+class _Controller extends Fake implements QRViewController {}
+
/// The shared scanner showing a page that needs no camera.
class _Scanner extends BarcodeScannerWrapper {
const _Scanner();
@@ -26,7 +36,7 @@ Future<List<String>> _logged(Future<void> Function() body) async {
}
/// Scans from a screen and closes the scanner with [scanned].
-Future<List<String>> _loggedByScan(WidgetTester tester, String? scanned) {
+Future<List<String>> _loggedByScan(WidgetTester tester, ScanResult? scanned) {
return _logged(() async {
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
final scan = const _Scanner().scan(
@@ -35,7 +45,9 @@ Future<List<String>> _loggedByScan(WidgetTester tester, String? scanned) {
await tester.pumpAndSettle();
Navigator.of(tester.element(find.text("scanner page"))).pop(scanned);
await tester.pumpAndSettle();
- await scan;
+ final result = await scan;
+ expect(result.failure, isNull);
+ expect(result.rawContent, scanned?.rawContent);
});
}
@@ -63,6 +75,95 @@ void main() {
expect(lines, contains(contains("Qr scanning cancelled")));
});
+ testWidgets("a successful scan returns and logs the exact debug payload", (
+ tester,
+ ) async {
+ const text = " example:data\n";
+ final lines = await _loggedByScan(
+ tester,
+ const ScanResult(rawContent: text),
+ );
+ expect(lines, contains(contains("qrResult content: $text")));
+ });
+
+ for (final (platform, canRequestAgain) in [
+ (TargetPlatform.iOS, false),
+ (TargetPlatform.android, true),
+ (TargetPlatform.android, false),
+ ]) {
+ testWidgets(
+ 'camera denial on $platform (can request again: $canRequestAgain)',
+ (tester) async {
+ final messenger = tester.binding.defaultBinaryMessenger;
+ const permissions = MethodChannel(
+ 'flutter.baseflow.com/permissions/methods',
+ );
+ final calls = <String>[];
+ messenger.setMockMethodCallHandler(permissions, (call) async {
+ calls.add(call.method);
+ return call.method == 'openAppSettings' || canRequestAgain;
+ });
+ addTearDown(
+ () => messenger.setMockMethodCallHandler(permissions, null),
+ );
+ // Provide the native view ID without creating a camera.
+ messenger.setMockMethodCallHandler(
+ SystemChannels.platform_views,
+ (call) async => 1,
+ );
+ addTearDown(
+ () => messenger.setMockMethodCallHandler(
+ SystemChannels.platform_views,
+ null,
+ ),
+ );
+
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ const host = Key('scanner host');
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ themeProvider.overrideWithValue(StateController(theme)),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: const SizedBox(key: host),
+ ),
+ ),
+ );
+ final scan = const BarcodeScannerWrapper().scan(
+ context: tester.element(find.byKey(host)),
+ );
+ await tester.pump();
+ final onPermissionSet = tester
+ .widget<QRView>(find.byType(QRView))
+ .onPermissionSet!;
+ onPermissionSet(_Controller(), true);
+ expect(find.byType(QrScanner), findsOneWidget);
+ onPermissionSet(_Controller(), false);
+ await tester.pumpAndSettle();
+
+ expect(find.byType(QrScanner), findsNothing);
+ if (canRequestAgain) {
+ expect(find.text("Open settings?"), findsNothing);
+ } else {
+ expect(find.text("Open settings?"), findsOneWidget);
+ await tester.tap(find.text("Continue"));
+ await tester.pumpAndSettle();
+ }
+ expect((await scan).failure, ScanFailure.cameraPermissionDenied);
+ expect(calls, [
+ if (platform == TargetPlatform.android)
+ 'shouldShowRequestPermissionRationale',
+ if (!canRequestAgain) 'openAppSettings',
+ ]);
+ },
+ variant: TargetPlatformVariant.only(platform),
+ );
+ }
+
testWidgets("a scanner that fails to open is logged and scans nothing", (
tester,
) async {
@@ -76,6 +177,7 @@ void main() {
});
expect(result.rawContent, isNull);
- expect(lines, contains(contains("Error opening QR code scanner dialog")));
+ expect(result.failure, ScanFailure.scannerError);
+ expect(lines, contains(contains("QR code scan failed")));
});
}Why this scored 25/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.