Search code examples
flutterdart

Crash type casting issues in Dart related to generic values and null checks, type '(String?) => void' is not a subtype of type '((dynamic) => void)?'


I am trying to figure out if widget.onChanged of RadioListTile<T> is not null, but it seems like dart is very strict when it comes to generics, any suggestion on how I can check it?
(I am a little new to Fluter/Dart )

 void testWidgetOnNUllDynamic(dynamic clbk) {
      if (clbk != null) {
        print('not null');
      }
    }
    
    void testWidgetOnNUllCallback(Widget widget) {
      if (widget is RadioListTile) {
        // if (widget.onChanged != null) {
        //   //type '(String?) => void' is not a subtype of type '((dynamic) => void)?'
        //   print('Crash here');
        // }
        //attempt to erase the type
        testWidgetOnNUllDynamic(widget.onChanged);
      }
    }

//This method is redundant 
    void testIfOnChangeIsNull(Widget widget) {
      testWidgetOnNUllCallback(widget);
    }

    test('when widget is RadioListTile onChange test', () {
// <String> - Can be anything 
      RadioListTile<String> widget = RadioListTile(value: 'value', activeColor: 0, toggleable: true, onChanged:(value) => debugPrint('Test'), groupValue: null,);
       testIfOnChangeIsNull(widget);
      
    });

I think that I understand the error I am not sure how to avoid it OR how to check of nallability without casting it to concrete type
Asked same question here
Thanks


Solution

  • The answer came from here The easiest work around was to do something like that:

     void testWidgetOnNUllCallback(Widget widget) {
          if (widget is RadioListTile) {
            if ((widget as dynamic).onChanged != null) {
              print('wont crash any more');
            }
          }
    }