skip to Main Content

I am trying to read a qr code string from an image using scan: ^1.6.0 package in flutter , but the result is displayed only after I hot reload the application.

but I want to print the result on the screen after the user picks an image file from gallery

My code:

class _ReadFromImgState extends State<ReadFromImg> {
  File? image;
  final ImagePicker picker = ImagePicker();
  String res = '';

  Future pickImage() async {
    setState(() async {
      final image = await picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final tmpfile = File(image.path);
      this.image = tmpfile;
      res = (await Scan.parse(image.path))!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Center(
          child: ElevatedButton(
              onPressed: () {
                pickImage();
              },
              child: const Text("choose image")),
        ),
        Center(
          child: Text(res),
        ),
      ],
    ));
  }
}

2

Answers


  1. Call setState after getting image like

     ElevatedButton(
        onPressed: () async{
          await pickImage(); // complete the fetch
          setState((){});
    
    Login or Signup to reply.
  2. setState((){}) should always be synchronous and only be used to update the state of the class. You are triggering an action inside setState which is an asynchronous call, Making setState((){}) asynchronous ie. setState(() async {}), makes it unclear when the state should be set.

    Replace your pickImage method with this,

     Future pickImage() async {
          final image = await picker.pickImage(source: ImageSource.gallery);
          if (image == null) return;
          var scanData = await Scan.parse(image.path) ?? "";
          setState(() {
            this.image = File(image.path);
            res = scanData;
          });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search