Search code examples
android-studiodartvoid

error in dart constructors can't have a return type


it is my code:

// import 'package:calculator/add.dart';
// import 'package:calculator/divide.dart';
// import 'package:calculator/multiple.dart';
// import 'package:calculator/subtract.dart';
import 'package:calculator/calculator.dart';
//top level or global variable
int number = 5;
class test{
    int a = 10; //instance variable
    static int b = 20; //static variables
    # void test(){
    print(number);
    }
}
void main(List\<String\> arguments){
    int local1 = 30; //definition local variables
    print(number);
    print(add(2, 3));
    print(divide(100, 10));
    print(multiple(2, 10));
    print(subtract(90, 9));
    }`end of code`

when I use void test(){ the Dart Analysis get error with this text: "constructors can't have a return type." what is my mistake? I try type code in android studio in dart programming language


Solution

  • Your main mistake is to not recognize that you are creating a constructor.

    The class test {...} declares a class named test. That's probably a mistake. Dart style says to use capitalized names for classes, so it should be:

    class Test {
     // ...
    }
    

    You probably just wrote some name because a name was needed, but the name of the class is reserved for constructors, so when you wrote:

     void test(){
       print(number);
     }
    

    in a class also named test, that is not a normal method, it's a constructor, and constructors can't have return types (because thy must return the class's type).

    If you rename the class to Test, that problem will go away.