简体   繁体   中英

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

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();
  }
}

You can use GetxService to share data in your app.

class SharedData extends GetxService {
  static SharedData get to => Get.find();
  final sharedText = ''.obs;

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

  @override
  void onClose() {
    super.onClose();
  }
}
 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';
      }
    }

   // assign value
   SharedData.to.sharedText.value = resultTxt;
  }

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM