Vishnubly
Vishnubly

Reputation: 749

Cannot have function with generic parameter in generic stateful widget

I was trying to create a generic stateful widget in flutter with a parameter as a function with a generic parameter like this:-

class MyWidget<T> extends StatefulWidget {
  MyWidget(
    {this.fn}
  );
  
  final void Function(T value)? fn;
  
  @override
  _MyWidgetState createState() => _MyWidgetState<T>();
}

class _MyWidgetState<T> extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return Text('Hello, World! ${widget.fn == null}');
  }
}

Which I then called like this:-

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget<double>(
            fn: (_) {},
          ),
        ),
      ),
    );
  }
}

But this does not produce any output, can anyone help me? This works perfectly fine in case of Stateless Widget and in case fn value is null.

Upvotes: 0

Views: 647

Answers (1)

Michael Horn
Michael Horn

Reputation: 4099

It's because _MyWidgetState doesn't know how to parameterize the type of its parent widget, so when you try to use widget.fn, the runtime is unable to resolve the type correctly.

To fix it, try this:

class _MyWidgetState<T> extends State<MyWidget<T>> {
                                              ^^^

Instead of this

class _MyWidgetState<T> extends State<MyWidget> {

Upvotes: 3

Related Questions