Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a class in Dart/Flutter

Tags:

flutter

dart

I have class A:

class A{
    String title;
    String content;
    IconData iconData;
    Function onTab;
    A({this.title, this.content, this.iconData, this.onTab});
}

How can i create class B that extends class A with additional variable like following:

class B extends A{
    bool read;
    B({this.read});
}

Tried with this but not working

let o = new B(
          title: "New notification",
          iconData: Icons.notifications,
          content: "Lorem ipsum doro si maet 100",
          read: false,
          onTab: (context) => {

          });
like image 252
anhnt Avatar asked Jul 04 '19 01:07

anhnt


People also ask

How do you extend a class in flutter?

You can inherit from or extend a class using the extends keyword. This allows you share properties and methods between classes that are similar, but not exactly the same. Also, it allows different subtypes to share a common runtime type so that static analysis doesn't fail.

What is extend in Dart?

In Dart, the extends keyword is typically used to alter the behavior of a class using Inheritance. The capability of a class to derive properties and characteristics from another class is called Inheritance. It is ability of a program to create new class from an existing class.

How do you extend a Dart function?

Dart has a Function type. This can be extended on and you can pass type parameters if you want. Here is an example from the changelog: extension CurryFunction<R, S, T> on R Function(S, T) { ... }


2 Answers

You have to define the constructor on the child class.

class B extends A {
  bool read;
  B({title, content, iconData, onTab, this.read}) : super(title: title, content: content, iconData: iconData, onTab: onTab);
}
like image 142
Vinicius Brasil Avatar answered Oct 03 '22 20:10

Vinicius Brasil


You can inherit from or extend a class using the extends keyword. This allows you share properties and methods between classes that are similar, but not exactly the same. Also, it allows different subtypes to share a common runtime type so that static analysis doesn't fail. (More on this below); The classic example is using different types of animals.

class Animal {
  Animal(this.name, this.age);
  
  int age;
  String name;

  void talk() {
    print('grrrr');
  }
}

class Cat extends Animal {
  // use the 'super' keyword to interact with 
  // the super class of Cat
  Cat(String name, int age) : super(name, age);
  
  void talk() {
    print('meow');
  }
  
}


class Dog extends Animal {
  // use the 'super' keyword to interact with 
  // the super class of Cat
  Dog(String name, int age) : super(name, age);
  
  void talk() {
    print('bark');
  }
  
}

void main() {
  var cat = Cat("Phoebe",1);
  var dog = Dog("Cowboy", 2);
  
  dog.talk();
  cat.talk();
}
like image 35
Suresh B B Avatar answered Sep 22 '22 12:09

Suresh B B