Flutter: Subtype Error when creating an widget with generics

Issue

I’m using viewmodels for my app that extend ChangeNotifier. To use them I’m trying to implement an generic base widget:


    class BasePageWidget<ViewModelType extends ChangeNotifier>
        extends StatefulWidget {
      final Function(ViewModelType vm) init;
      final Widget Function(BuildContext context, ViewModelType vm) builder;
      final ViewModelType _vm = sl.get<ViewModelType>();

      BasePageWidget({Key key, this.init, this.builder}) : super(key: key);

      @override
      _BasePageWidgetState createState() => _BasePageWidgetState<ViewModelType>();
    }

    class _BasePageWidgetState<ViewModelType extends ChangeNotifier>
        extends State<BasePageWidget> {
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider<ViewModelType>.value(
          value: widget._vm,
          child: Consumer<ViewModelType>(
            builder: (context, _vm, child) => widget.builder(context, widget._vm),
          ),
        );
      }

      @override
      void initState() {
        if (widget.init != null) {
          widget.init(widget._vm);
        }
        super.initState();
      }
    }

The base widget has an type parameter and gets an instance of the viewmodel with the service locator of the get_it package.

But when im trying to run the app, when using the widget:

void main() {
  setup();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: BasePageWidget<ViewModel>(
        init: (vm) => vm.setTitle("Set init State"),
        builder: (context, vm) => FlatButton(
          onPressed: () {
            vm.setTitle("State2");
          },
          child: Text(vm.text),
        ),
      ),
    );
  }
}

Flutter throws an runtime error:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building Builder:
flutter: type '(ViewModel) => void' is not a subtype of type '(ChangeNotifier) => dynamic'
flutter:
flutter: The relevant error-causing widget was:
flutter:   MaterialApp 
lib/main.dart:15
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      _BasePageWidgetState.initState 
package:viewmodel_test/base_widget.dart:31
flutter: #1      StatefulElement._firstBuild 
package:flutter/…/widgets/framework.dart:4456
flutter: #2      ComponentElement.mount 
package:flutter/…/widgets/framework.dart:4302
flutter: #3      Element.inflateWidget 
package:flutter/…/widgets/framework.dart:3297
flutter: #4      Element.updateChild 
package:flutter/…/widgets/framework.dart:3091
flutter: #5      SingleChildRenderObjectElement.mount 

The errors seems to be caused by the function arguments:

final Function(ViewModelType vm) init;
final Widget Function(BuildContext context, ViewModelType vm) builder;

When I exchange the generic type (ViewModelType) with dynamic, the app runs fine (of course without the type safety):

final Function(ViewModelType vm) init;
final Widget Function(BuildContext context, ViewModelType vm) builder;

Any ideas how to make it run with the generic parameters?

Here ist my viewmodel:

class ViewModel extends ChangeNotifier {
  String text = '';

  void setTitle(String text) {
    this.text = text;
    notifyListeners();
  }
}

and the get_it setup:

GetIt sl = GetIt.instance;

Future<void> setup() async {
  sl.registerFactory(() => ViewModel());
}

Solution

You can copy paste run full code below
please change State<BasePageWidget> to State<BasePageWidget<ViewModelType>>

from

class _BasePageWidgetState<ViewModelType extends ChangeNotifier>
    extends State<BasePageWidget> {

to

class _BasePageWidgetState<ViewModelType extends ChangeNotifier>
extends State<BasePageWidget<ViewModelType>> {

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:get_it/get_it.dart';

class BasePageWidget<ViewModelType extends ChangeNotifier>
    extends StatefulWidget {
  final Function(ViewModelType vm) init;
  final Widget Function(BuildContext context, ViewModelType vm) builder;
  final ViewModelType _vm = sl.get<ViewModelType>();

  BasePageWidget({Key key, this.init, this.builder}) : super(key: key);

  @override
  _BasePageWidgetState createState() => _BasePageWidgetState<ViewModelType>();
}

class _BasePageWidgetState<ViewModelType extends ChangeNotifier>
    extends State<BasePageWidget<ViewModelType>> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ViewModelType>.value(
      value: widget._vm,
      child: Consumer<ViewModelType>(
        builder: (context, _vm, child) => widget.builder(context, widget._vm),
      ),
    );
  }

  @override
  void initState() {
    if (widget.init != null) {
      widget.init(widget._vm);
    }
    super.initState();
  }
}

class ViewModel extends ChangeNotifier {
  String text = '';

  void setTitle(String text) {
    this.text = text;
    notifyListeners();
  }
}

GetIt sl = GetIt.instance;

Future<void> setup() async {
  sl.registerFactory(() => ViewModel());
}

void main() {
  setup();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: BasePageWidget<ViewModel>(
        init: (vm) => vm.setTitle("Set init State"),
        builder: (context, vm) => Scaffold(
          body: Center(
            child: FlatButton(
              onPressed: () {
                vm.setTitle("State2");
              },
              child: Text(vm.text),
            ),
          ),
        ),
      ),
    );
  }
}

Answered By – chunhunghan

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.