Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter StatefulWidget widgets and generics

Tags:

flutter

How can I pass generic type to the State of a StatefulWidget, Here I want to use my generics in myMethod<T>

class MyWidget<T> extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
  
  myMethod<T>(){
    
  }
}
like image 608
WebMaster Avatar asked Nov 24 '25 22:11

WebMaster


1 Answers

You just provide the type in your state full widget and then pass it way down to its state:

class MyWidget<T> extends StatefulWidget {
  @override
  _MyWidgetState<T> createState() => _MyWidgetState<T>();
}

class _MyWidgetState<T> extends State<MyWidget<T>> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
  
  myMethod<T>() {
    
  }
}

Usage: MyWidget<String>()

like image 129
Pedro Massango Avatar answered Nov 27 '25 12:11

Pedro Massango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!