13

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

3 Answers 3

26

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

8

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

2
  • 1
    Expected to find '>'.
    – A.A
    Dec 13, 2020 at 6:06
  • 1
    you just saved my day, sir Jul 20 at 22:48
1

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.