12

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>(){
    
  }
}
WebMaster
  • 3,050
  • 4
  • 25
  • 77

3 Answers3

23

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>()

DJafari
  • 12,955
  • 8
  • 43
  • 65
Pedro Massango
  • 4,114
  • 2
  • 28
  • 48
8

_MyWidgetState need to extends State<MyWidget<T>> not just State<MyWidget> and then you can use T within _MyWidgetState

ikerfah
  • 2,612
  • 1
  • 11
  • 18
0

Here's how the Flutter team solves this issue inside the FutureBuilder widget. Instead of having a return type of _MyWidgetState<T> for the createState(), you would need State<MyWidget<T>>.

State<MyWidget<T>> createState() => _MyWidgetState<T>();
icnahom
  • 56
  • 5