ZXing 扫描仪上的后退按钮不起作用(Xamarin Forms)

Backbutton on ZXing Scanner doesn´t works (Xamarin Forms)

我正在尝试在我的 Xamarin Forms 项目中实施条码扫描器。当我按下扫描页面上的后退按钮时,我的应用程序崩溃了。我收到以下错误:System.NullReferenceException:'Object reference not set to an instance of an object.'

这是我的代码:

ScanService.cs

public interface ScanningService
{
    Task<string> ScanAsync();

}

我背后的代码:

var scanner = DependencyService.Get<ScanningService>();
        var result = await scanner.ScanAsync();
        if (result != null){.....}

QRscanningService(在 Android 上):

   class QrScanningService : ScanningService
    {
       

        public async Task<string> ScanAsync()
        {

            var optionsCustom = new MobileBarcodeScanningOptions();

            var scanner = new MobileBarcodeScanner()
            {
                TopText = "Acerca la cámara",
                BottomText = "Toca la pantalla para enfocar",

            };
            var scanResult = await scanner.Scan(optionsCustom);

            return scanResult.Text;
        }

    }

任何贡献都将得到赞赏。

我认为错误发生在 QRscanningService 内部(在 Android 上)。

这是因为您正在尝试使用 scanResult 中的“文本”,而 scanResult 为 null

为避免这种情况,请将最后一行更改为如下内容:

return scanResult == null ? null: scanResult.Text;

我在后面的代码中使用以下代码解决了它:

var overlay = new ZXingDefaultOverlay
{
    ShowFlashButton = true,
    TopText = "Toca la pantalla para enfocar",
    BottomText = string.Empty
};

overlay.BindingContext = overlay;

scanPage = new ZXingScannerPage(null, overlay);
            
overlay.FlashButtonClicked += (s, ed) =>
{
    scanPage.ToggleTorch();
};

scanPage.OnScanResult += (result) =>
{
    scanPage.IsScanning = false;

    Device.BeginInvokeOnMainThread(() =>
    {
        _ = Navigation.PopModalAsync();
        try
        {
            TxtidR.Text = result.Text;
        }
        catch (Exception)
        {
            throw;
        }
    });
};

await Navigation.PushModalAsync(scanPage);
var scanner = DependencyService.Get<ScanningService>();
}

希望对你有用!