build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  bool isPoping = false;
  void setValue(String text) {
    value.value = text;
  }

  RegExp selectRegex() {
    switch (ocrRecognizingType) {
      case OcrRecognizingType.word:
        return RegExp(r'[A-Za-z]{3,}');
      case OcrRecognizingType.numeric:
        return RegExp(r'[0-9]+(\.[0-9]+)?');
      case OcrRecognizingType.phone:
        return RegExp(r'\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b');
      case OcrRecognizingType.email:
        return RegExp(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b',
            multiLine: true);
    }
  }

  String filterRecognizedText(String recognizedText) {
    RegExp regexToAply = selectRegex();

    String filteredText = ocrRecognizingType == OcrRecognizingType.numeric
        ? recognizedText
            .replaceAll(",", ".")
            .replaceAll("l", "1")
            .replaceAll("I", "1")
            .replaceAll("O", "0")
            .replaceAll("o", "0")
        : recognizedText.split(" ").first;

    List<Match> matches = regexToAply.allMatches(filteredText).toList();

    String stringReturn = "";
    for (var match in matches) {
      stringReturn += "${match.group(0)} \n";

      if (matches.indexOf(match) == (limitOfMatches)) {
        return stringReturn;
      }
    }

    return stringReturn;
  }

  Future<void> processOcr(InputImage inputImage) async {
    final TextRecognizer textRecognizer =
        TextRecognizer(script: TextRecognitionScript.latin);

    RecognizedText textRecognized =
        await textRecognizer.processImage(inputImage);

    setValue(filterRecognizedText(textRecognized.text));
  }

  Future<void> processBarcode(InputImage inputImage) async {
    final List<BarcodeFormat> barcodeFormats = [BarcodeFormat.all];

    final BarcodeScanner barcodeScanner =
        BarcodeScanner(formats: barcodeFormats);

    List<Barcode> readedBarcodes =
        await barcodeScanner.processImage(inputImage);

    if (readedBarcodes.isNotEmpty) {
      String? readedValue = readedBarcodes.first.displayValue;

      setValue(readedValue ?? "");
    }
  }

  Future<void> analyseImage(CameraImage inputImage) async {
    isProcessing.value = true;

    (InputImage, img.Image, File) recordReturn = await compute(cropImage, (
      inputImage,
      RootIsolateToken.instance!,
      heightInterestFactor,
      widthInterestFactor,
      MediaQuery.of(context).orientation
    ));

    if (onImageAvailable != null) {
      onImageAvailable!(recordReturn.$2);
    }

    if (imageFileCallback != null) {
      imageFileCallback!(recordReturn.$3);
    }

    if (readerType == ReaderType.ocr) {
      await processOcr(recordReturn.$1);
    }

    if (readerType == ReaderType.barcode) {
      await processBarcode(recordReturn.$1);
    }

    onValueReaded(value.value);

    isProcessing.value = false;
  }

  Future<void> onImageStreamed(
      CameraImage cameraImage, BuildContext cameraContext) async {
    // Use '&&' para garantir que ambas as condições sejam verdadeiras
    if (!isProcessing.value && !isPoping) {
      try {
        isProcessing.value = true; // Move a definição para cá

        await analyseImage(cameraImage);

        if (autopop &&
            readerType == ReaderType.barcode &&
            value.value != null &&
            value.value != "") {
          isPoping = true;
          // ignore: use_build_context_synchronously
          Navigator.of(context).pop();
        }

        isProcessing.value = false; // Move a definição para cá
      } on TypeError {
        isProcessing.value =
            false; // Garanta que a flag seja redefinida em caso de erro
        return;
      }
    }
  }

  return Scaffold(
    body: CameraViewer(
      deviceOrientation: deviceOrientation,
      onImageStreamed: onImageStreamed,
      widget: Stack(
        children: [
          Center(
              child: CustomPaint(
            painter: InterestZone(
                heightInterestFactor: heightInterestFactor,
                widthInterestFactor: widthInterestFactor,
                borderColors: ocrBorderColor),
            child: ListenableBuilder(
              listenable: value,
              builder: (context, child) => Visibility(
                  visible: value.value != null,
                  child: Center(
                    child: Text(value.value ?? "",
                        style: TextStyle(color: ocrTextColor)),
                  )),
            ),
          )),
          Builder(builder: (context) {
            if (child == null) {
              return Container();
            }

            return child!;
          })
        ],
      ),
    ),
  );
}