如何修复错误:参数类型'Function'不能分配给参数类型"void Function()?- "功能"来自'dart:core'



我正试图将一个函数从main.dart传递到一个小部件,但我收到了以下错误:

错误:无法将参数类型"Function"分配给参数类型"void Function((?"。

  • "函数"来自"dart:core">

FilterScreen类

import 'package:delimails/widgets/main_drawer.dart';  import 'package:flutter/material.dart';
class FilterScreen extends StatefulWidget {   static const routeName = '/filter';    final Function saveFilters;
FilterScreen(this.saveFilters);
@override   
_FilterScreenState createState() => _FilterScreenState(); }
class _FilterScreenState extends State<FilterScreen> {  

@override   Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Your favorites'),
actions: [
IconButton(icon : Icon(Icons.save), onPressed: **widget.saveFilters**)
],
), 
// main class : class MyApp extends StatefulWidget {   // This widget is the root of your application.   @override   _MyAppState createState() => _MyAppState(); }
class _MyAppState extends State<MyApp> {  Map<String, bool> _filters = {    'gluten' : false,    'lactose' : false,    'vegan' : false,    'vegetarian' : false,  };
void _setFilters (Map<String, bool> filterData){    print('we are here !');  } 
@override   Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Colors.cyan[300],
accentColor: Colors.orange[100],
canvasColor: Color.fromRGBO(255, 254, 229, 1),
fontFamily: 'Releway',
textTheme: ThemeData.light().textTheme.copyWith(
bodyText1: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
bodyText2: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
headline6: TextStyle(
fontSize: 20,
fontFamily: 'RobotoCondensed',
fontWeight: FontWeight.bold,
))),
// home: CategoriesScreen(),
routes: {    
'/': (ctx) => TabsScreen(),
'/categories': (ctx) => CategoriesScreen(),
CategoryMealsScreen.routeName: (ctx) => CategoryMealsScreen(),
MealDetailScreen.routeName: (ctx) => MealDetailScreen(),
FilterScreen.routeName : (ctx) => FilterScreen(_setFilters),
},


);   } }

对于未格式化的代码很难说。

但是,看起来您将变量/参数saveFilters定义为Function,它可以是任何可能的函数(String Function(BuildContext)List<int> Function(int, int)等(,与IconButton(void Function()VoidCallback(的参数onPressed的预期类型不匹配。

你能试着明确地指定saveFiltersvoid Function()的类型吗?

class FilterScreen extends StatefulWidget {
FilterScreen(this.saveFilters);
static const routeName = '/filter';
final void Function() saveFilters;
@override
_FilterScreenState createState() => _FilterScreenState();
}
// ... The rest of your code

最新更新