flutterdartsetstateimagepicker

The UI gets updated only after hot reload


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),
        ),
      ],
    ));
  }
}

Solution

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