Search code examples
flutterdartmobileabstract-class

Error in flutter Abstract classes can't be instantiated


currently I am studying Flutter and Dart, and when writing code, I'm getting this error message: "Abstract classes can't be instantiated. : 35".

I don't know what to do, I followed a tutorial video and it seemed like everything was the same as in the source material, but I still get the error.

     @override
  Widget build(BuildContext context){
    return Center(
      child: Column(
        children: [
          IconButton(onPressed: () {
            if (suschestvuet == true) {
              suschestvuet = false;
            }
            else{
              suschestvuet = true;
            }
            setState(() {});
          }, icon: Icon(Icons.cabin)),

Bottom 35 stitches

if (suschestvuet) const rebenok1() else Container(),

        ],
      ),
    );
  }
}

abstract class rebenok1 extends StatefulWidget{
  const rebenok1 ({Key? key}) : super (key: key);

  @override
  State<rebenok1> createState() => _rebenok1State();
}

class _rebenok1State extends State<rebenok1>{

Solution

  • That's right! In Flutter, as in many object-oriented programming languages, abstract classes cannot be instantiated directly. Abstract classes serve as blueprints for other classes to inherit from but cannot be used to create objects on their own. They can contain abstract methods (methods without a defined implementation) that must be implemented by any class that extends them. To use an abstract class in Flutter, you need to create a concrete class that extends the abstract class and provides implementations for its abstract methods.

    Look your code at this line:

    abstract class rebenok1 extends StatefulWidget{
    

    You need to learn the basics of programming language.

    Here an example to create an abstract class.

    // Abstract class
    abstract class Shape {
      // Abstract method
      void draw();
      
      // Regular method
      void display() {
        print('Displaying shape...');
      }
    }
    
    // Concrete class extending the abstract class
    class Circle extends Shape {
      @override
      void draw() {
        print('Drawing Circle');
      }
    }
    
    void main() {
      // This won't work - Can't instantiate an abstract class
      // Shape shape = Shape();
    
      // Create an instance of the concrete class
      Circle circle = Circle();
      circle.draw(); // Output: Drawing Circle
      circle.display(); // Output: Displaying shape...
    }