The method isn't defined for the class - Flutter
Solution 1
I don't recommend writing imports by your self, when you have some widget or function that is not imported an error will be highlighted with indicating suggestions to fix that . here is an example :
-
call your function or widget, here I have a widget to call :
-
as you can see an error is highlighted suggesting to import
this will prevent such errors for you in the future
Solution 2
I to had a similar issue. Even though my import statement is correct i had this issue.
Then i have did "flutter clean" and after "flutter run" it worked.
So, just clean the build using "flutter clean" and see. hope it works.

Vaibav79
Updated on July 09, 2022Comments
-
Vaibav79 5 months
I'm new to flutter and have been trying to make a simple quiz app. I've encountered an error and I'm not sure what is wrong.
Error:
Compiler message: lib/main.dart:37:17: Error: The method 'Answer' isn't defined for the class '_MyAppState'. - '_MyAppState' is from 'package:project2/main.dart' ('lib/main.dart'). Try correcting the name to the name of an existing method, or defining a method named 'Answer'. Answer(), ^^^^^^ lib/main.dart:38:17: Error: The method 'Answer' isn't defined for the class '_MyAppState'. - '_MyAppState' is from 'package:project2/main.dart' ('lib/main.dart'). Try correcting the name to the name of an existing method, or defining a method named 'Answer'. Answer(), ^^^^^^ lib/main.dart:39:17: Error: The method 'Answer' isn't defined for the class '_MyAppState'. - '_MyAppState' is from 'package:project2/main.dart' ('lib/main.dart'). Try correcting the name to the name of an existing method, or defining a method named 'Answer'. Answer() ^^^^^^
main.dart:
import 'package:flutter/material.dart'; import './questions.dart'; import './answer.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return _MyAppState(); } } class _MyAppState extends State<MyApp> { var _questionIndex = 0; var _questions = ["Question 1?", "Question 2?", "Question 3?"]; void _answerQuestion() { setState(() { _questionIndex = _questionIndex + 1; }); print("You answered the question!"); } Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Quiz"), ), body: Column( children: <Widget>[ Question(_questions[_questionIndex]), Answer(), Answer(), Answer() ], ))); } }
answer.dart:
import 'package:flutter/material.dart'; class Answer extends StatelessWidget { @override Widget build(BuildContext context) { return Container( width: double.infinity, color: Colors.blue, child: RaisedButton(child: Text("Answer 1"), onPressed: null)); } }
I have used the same class name and imported the right file into main.dart. I'm not sure what's wrong. Can someone please point it out to me. Thanks in advance!