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 ..
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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With