Reputation: 4101
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>(){
}
}
Upvotes: 20
Views: 6868
Reputation: 76
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>();
Upvotes: 2
Reputation: 5015
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>()
Upvotes: 39
Reputation: 2862
_MyWidgetState
need to extends State<MyWidget<T>>
not just State<MyWidget>
and then you can use T
within _MyWidgetState
Upvotes: 11