Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from a class gives me an error

Tags:

flutter

dart

I'm trying to run a function in another class. When I do that, I get an error message saying the following:

'_makeGetRequest' must have a method body because 'Home' isn't abstract. Try making 'Home' abstract, or adding a body to '_makeGetRequest'.dart(concrete_class_with_abstract_member)

Here's the code:

class Home extends StatelessWidget {
  _makeGetRequest(); // Error is here

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('CRUD Bro')),
      body: Center(
        child: Text('My App'),
      ),
    );
  }
}

_makeGetRequest() async {
    print('hello');
}

I tried making the Home class abstract, but the program doesn't work then. How can I call a function inside this class?

like image 274
Jessica Avatar asked Nov 22 '25 03:11

Jessica


1 Answers

According to your code, The method is in the same class not another, am I right?

Anyway, This error message is NOT saying "make it abstract to solve your problem", but in fact the compiler got confused, it reads this line:

_makeGetRequest();

then the compiler starts thinking like this: "hmmm this is a function's signature(function without body!), so this developer is trying to create an abstract class(because abstract class can have function without body) but this developer forgot to add abstract keyword like this abstract class Home... so, is it an abstract class and 'abstract' keyword is missing, or a normal class and function's body is missing?!!" so this lovely compiler will tell you its thoughts in an error message:

Try making 'Home' abstract, or adding a body to '_makeGetRequest'...

but both options are not solutions, it just got confused as I said.

But why this is the case?

because class is like the idea of 'Car', you can't drive the idea of car, but you need to create an object from that idea first, a BMW, then you can drive that BMW(in another word, you can call methods on objects not classes, because you can drive car's object but not the idea of Car).

To call methods you have at least these 4 options:

1- (In any language) to call methods from different class, create object first in that different class, then call them on that object: Do NOT use this with flutter's widgets, see option 4 below for that

class A {
  B b = B();
  b.makeGetRequest();
}

//..
class B {
  makeGetRequest() async { // NOT  PRIVATE(NO _)
    print('hello');
  }
}

2- (In any language) to call methods in same class, call it in the constructor, like Doc's answer.

3- (In Flutter) to call methods in same class, call it in the Build, like Doc's answer also.

4- (In Flutter) to call methods in different class, you need a bloc, see my answer here for more details.

like image 67
Jehad Nasser Avatar answered Nov 24 '25 22:11

Jehad Nasser