Home > OS >  VoidCallback passed to sub-widget not doing anything
VoidCallback passed to sub-widget not doing anything

Time:01-18

I'm calling a VoidCallback as part of my main app that gets passed to a sub-widget in the routes table, but when I use that function in the sub-widget, it does not do anything (Does not even trigger the print statement that is part of the function).

Is there any way I need to declare it differently to make it work? I was just going to use Function types, but I have null safety on, so this was the only way I could get it to stop creating build errors.

My home app creates this Voidcallback (_setFilters) that accepts this <String, bool> map, and .

class _MyAppState extends State<MyApp> {
  Map<String, bool> _filters = {
    'gluten': false,
    'lactose': false,
    'vegan': false,
    'vegetarian': false,
  };

  List<Meal> _availableMeals = DUMMY_MEALS;

  void _setFilters(Map<String, bool> filterData) {
    setState(() {
       // Sets state items
       print('THIS IS WORKING!!');
    });
  }

That is passed to the FilterScreen as part of the routes table:

      routes: {
        '/': (ctx) => TabScreen(),
        CategoryMealsScreen.routeName: (ctx) =>
            CategoryMealsScreen(_availableMeals),
        MealDetailScreen.routeName: (ctx) => MealDetailScreen(),
        FilterScreen.routeName: (ctx) => FilterScreen(_filters, _setFilters),
      },

The function is supposed to be instantiated within the StatefulWidget's property saveFilters:

class FilterScreen extends StatefulWidget {
  static const routeName = '/filters';

  final void Function(Map<String, bool>) saveFilters;
  final Map<String, bool> currentFilters;

  FilterScreen(this.currentFilters, this.saveFilters);

  @override
  State<FilterScreen> createState() => _FilterScreenState();
}

And then it gets called as part of the IconButton whenever that is pressed:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Your Filters'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.save),
            onPressed: () => () {
              final selectedFilters = {
                'gluten': _glutenFree,
                'lactose': _lactoseFree,
                'vegan': _vegan,
                'vegetarian': _vegetarian,
              };
              widget.saveFilters(selectedFilters);
            },
          ),
        ],
      ),

CodePudding user response:

onPressed is a function which doesn't return anything it means its void. by doing onPressed: () => this you actually returning a function instead pointing it.So correct your icon button onpressed code like this.

onPressed:() {
  final selectedFilters = {
    'gluten': _glutenFree,
    'lactose': _lactoseFree,
    'vegan': _vegan,
    'vegetarian': _vegetarian,
  };
  widget.saveFilters(selectedFilters);
},
  •  Tags:  
  • Related