0
votes

I am new to flutter and I get the error:

error : The argument type 'Function' can't be assigned to the parameter type 'void Function()'

I built a meal app.

I added a simple Drawer(). I get the error when I open the drawer.

import 'package:flutter/material.dart';
import 'package:recipes/screens/filters_screen.dart';

class MainDrawer extends StatelessWidget {
  Widget buildListTile(String title, IconData icon, Function tapHandler) {
    return ListTile(
        leading: Icon(
          icon,
          size: 26,
        ),
        title: Text(
          title,
          style: TextStyle(
              fontFamily: 'RobotoCondensed',
              fontSize: 24,
              fontWeight: FontWeight.bold),
        ),
        onTap:tapHandler
    );
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: Column(
      children: [
        Container(
          height: 120,
          width: double.infinity,
          padding: EdgeInsets.all(20),
          alignment: Alignment.centerLeft,
          color: Theme.of(context).accentColor,
          child: Text(
            'Cooking up!',
            style: TextStyle(
                fontWeight: FontWeight.w900,
                fontSize: 30,
                color: Theme.of(context).primaryColor),
          ),
        ),
        SizedBox(
          height: 20,
        ),
        buildListTile('Meals', Icons.restaurant,()  {
          Navigator.of(context).pushNamed('/');
        }),
        buildListTile('Filters', Icons.settings, ()  {
          Navigator.of(context).pushNamed(FiltersScreen.routeName);
        }),
      ],
    ));
  }
}
2

2 Answers

1
votes

Can you try to specify the type of tapHandler in your buildListTile method?

  Widget buildListTile(String title, IconData icon, void Function() tapHandler) {
/* ... The rest of your method */
}
0
votes

Dart has support for strong function types. This means that, in addition to the type Function, you can also specify the types of the parameters and return type in your function type. For example:

String example(int i) => 'Hello $i';

var String Function(int) function = example;

The error you are getting when you pass tapHandler to ListTile.onTap is basically saying: "I need a function that takes no parameters, and returns void, but you gave me any function".

For example, you could call:

buildListTile('example', Icons.add, (String s) => null)

which is not a void Function() as ListTile requires.

To fix it, change buildListTile to:

Widget buildListTile(String title, IconData icon, void Function() tapHandler) ...