Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the base class of a flutter app

Tags:

flutter

dart

Being new to Dart, I am not sure how I could extend the class of my statefull widget. This is what one of my class looks like

class HomeState extends State<Home>
{
} 

What I would like to do is to make the HomeState class inherit some methods from my custom class. Which would be something like this

class CustomClass
{
   void DisplayBusyDialog()
   {
         ......
   }
}

I know in Dart like Java you cannot inherit from multiple class (unlike C++). My question is what would I need to do to have HomeState inherit from CustomClass ? Will my custom class need to inherit from StatefulWidget and then have HomeState class extend CustomClass ? what about the template State how do I handle that in my custom Class? Any suggestions would be appreciated ..

like image 830
MistyD Avatar asked Nov 29 '22 08:11

MistyD


2 Answers

What you'll want is mixin, which allows multiple "extends".

class Bar {
  bar() {}
}

mixin Mixin {
  foo() {}
}

class Foo extends Bar with Mixin {
  hello() {
    foo();
    bar();
  }
}

And if you need your mixin the access fields from the base-class:

mixin Mixin on Bar {
  foo() {
    bar();
  }
}
like image 168
Rémi Rousselet Avatar answered Dec 05 '22 00:12

Rémi Rousselet


According to Dart programming language, the mixins has the solution to extend multiple parent classes. Anyhow if you want to follow the traditional object-oriented concept you can create an abstract class with a generic type.

abstract class _BaseStatefulState<T extends StatefulWidget> extends State<T> {

  _BaseStatefulState() {
    // Parent constructor
  }

  void baseMethod() {
    // Parent method
  }
}

Your StatefulWidget should be extended from the base like below:

class _MainScreenState extends _BaseStatefulState<MainScreen> {}

Example StatefulWidget:

import 'package:flutter/material.dart';

class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends _BaseStatefulState<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text("Test")),
    );
  }
}

abstract class _BaseStatefulState<T extends StatefulWidget> extends State<T> {

  _BaseStatefulState() {
    // Parent constructor
  }

  void baseMethod() {
    // Parent method
  }
}

Source reference:
https://gist.github.com/aslamanver/e1360071f9caff009101eb190a38d4cb

Flutter mixin documentation:
https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins

like image 34
Googlian Avatar answered Dec 05 '22 00:12

Googlian