skip to Main Content

I need have this function in a parent widget

User? _user;

void _onChangeUser(User? user) {
  setState(() {
    _user = user;
  });
}

I want to pass it to a child widget that receives a function with a dynamic argument, so on the parent widget build method I do:

return _ChildView(
   onPress:  _onChangeUser,
);

And on my child widget I want to pass this function, but let it have a dynamic argument, like this:

class _ChildView extends StatelessWidget {
  const _ChildView({
    Key? key,
    required this.onPress,
}) : super(key: key);

final ValueChanged<dynamic> onPress;

However, flutter is not allowing this. The argument type ‘void Function(User?)’ can’t be assigned to the parameter type ‘void Function(dynamic)’. I would expect to be able to assign a User? to a dynamic value.

How do I go about this?

I have also tried

final Function(dynamic) onPress;

but it doesn’t work either

2

Answers


  1. Your function inside _ChildView has a type dynamic as parameter, instead your function _onChangeUser has a type of User? as a parameter.

    If you want the onPress function inside _ChildView to accept arguments of different types each time it is called, you can define it to accept a generic type T as follows:

        class _ParentViewState extends State<ParentView> {
          User? _user;
    
          void _onChangeUser(User? user) {
            setState(() {
              _user = user;
            });
          }
    
          @override
          Widget build(BuildContext context) {
            return _ChildView(onPress: _onChangeUser);
          }
        }
    
        class _ChildView<T> extends StatelessWidget {
          final Function(T) onPress;
          const _ChildView({Key? key, required this.onPress}) : super(key: key);
    
          @override
          Widget build(BuildContext context) {
            return Container();
          }
        }
    
    Login or Signup to reply.
  2. Change

    final Function(dynamic) onPress
    

    to a general Function type

    final Function onPress
    

    and call it with

    onPress.call();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search