Bill_The_Coder
Bill_The_Coder

Reputation: 2510

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

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.

Upvotes: 1

Views: 2227

Answers (3)

Addisu Alemayehu
Addisu Alemayehu

Reputation: 1

You can not create setState on pickImage class your move your setState methode to _pickImageState

   class pickImage extends StatefulWidget {
 pickImage({Key? key}) : super(key: key);
 
  @override
  _pickImageState createState() => _pickImageState();
}

class _pickImageState extends State<pickImage> {
 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
  Widget build(BuildContext context) {
    return AlertDialog(
      
    );
  }
}

Upvotes: 0

YoBo
YoBo

Reputation: 2529

You need to move getImage inside _pickImageState.

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

Documentation

Upvotes: 1

nvoigt
nvoigt

Reputation: 77304

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.

Upvotes: 1

Related Questions