The method 'setState' isn't defined for the type 'pickImage'

Viewed 1293

I am using a stateful widget,but keep getting red line under my setState method with this error:

The method 'setState' isn't defined for the type 'pickImage'.

My Flutter Version:

Flutter 2.0.4 • channel stable 

ImagePicker Package Version:

  image_picker: ^0.7.4

This is the code:

class pickImage extends StatefulWidget {

  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {  //Keep getting red line here(under setState)
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }
  @override
  _pickImageState createState() => _pickImageState();
}

class _pickImageState extends State<pickImage> {
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      
    );
  }
}

I have googled this issue, but still can't find an appropriate answer, that's why came here.

2 Answers

You need to move getImage inside _pickImageState.

The setState method is a member of the State class. Not the StatefulWidget class.

Documentation

The setState method (see documentation) is a member of the State<T> class. Not the StatefulWidget class.

That means you can call it in classes derived from State<T> like your _pickImageState, but not in classes that are not. Like your class pickImage, where you are trying to call your function new.

You should be able to move the whole getImage method into your _pickImageState class.

Related