How to save the state of a var using getX in flutter?

Issue

Screenshot:
Text Recognition Page

The text detected from an image is saved in "var resultTxt", how can I save the state of all the lines detected by the ML model and use it on another page?

Text Recognition Code:

 doTextRecog() async {
    resultTxt = '';
    final FirebaseVisionImage visionImage =
        FirebaseVisionImage.fromFile(_selectedFile);
    final VisionText visionText =
        await textRecognizer.processImage(visionImage);

    for (TextBlock block in visionText.blocks) {
      for (TextLine line in block.lines) {
        resultTxt += line.text + '\n';
      }
    }

    setState(() {
      resultTxt;
      print(resultTxt);
    });
    // textRecognizer.close();
  }

I’m already using the getX controller for my image path, but I’m not sure how to save a var with multiple lines of text and use it on another page.
Controller Code:

class PollImageController extends GetxController {
  RxString imageDisplay = ''.obs;

  @override
  void onInit() {
    super.onInit();
  }

  void setImage(String image) {
    imageDisplay.value = image;
  }

  @override
  void onClose() {
    super.onClose();
  }
}

Solution

You could also just handle all your Text Recognition functionality in a dedicated GetxController class.

Then you could call doTextRecog() and access the updated RxString resultTxt value from anywhere.

class TextRecognitionController extends GetxController {
  RxString resultTxt = ''.obs; 

  doTextRecog() async {
    final FirebaseVisionImage visionImage =
        FirebaseVisionImage.fromFile(_selectedFile);
    final VisionText visionText =
        await textRecognizer.processImage(visionImage);

    for (TextBlock block in visionText.blocks) {
      for (TextLine line in block.lines) {
        resultTxt.value += line.text + '\n';
      }
    }
    
    print(resultTxt.value);
    // textRecognizer.close();
  }
}

Answered By – Loren.A

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.