AI: 这个报错是因为 onTap 参数的类型被声明为 Function,而它应该是可空的 void Function()。你可以将 Function 改为 void Function()? 或者使用 Function()? 来解决这个问题。

import 'package:flutter/material.dart';
import 'package:marketky/constant/app_color.dart';
import 'package:marketky/core/model/Search.dart';

class SearchHistoryTile extends StatelessWidget {
  SearchHistoryTile({required this.data, required this.onTap});

  final SearchHistory data;
  final void Function()? onTap; // 修改为可空函数

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap, // 使用 onTap
      child: Container(
        width: MediaQuery.of(context).size.width,
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: AppColor.primarySoft,
              width: 1,
            ),
          ),
        ),
        child: Text('${data.title}'),
      ),
    );
  }
}

解释:

  • Flutter 中的 GestureDetector 组件的 onTap 属性接受一个 void Function() 类型的回调函数,这个回调函数表示点击事件发生时需要执行的代码。
  • 错误提示 'The argument type 'Function' can't be assigned to the parameter type 'void Function()?'' 意思是,你传递给 onTap 的参数类型是 Function,而它应该是一个可空的 void Function() 类型。
  • 解决方法是将 onTap 的类型声明为 void Function()?,这样它就可以接受一个可空函数或 null 值。
  • 使用 Function()? 也可以,它表示一个可空的函数,但是 void Function()? 更明确地表示函数的返回值类型为 void
Flutter onTap 报错:'The argument type 'Function' can't be assigned to the parameter type 'void Function()?'

原文地址: https://www.cveoy.top/t/topic/oh3U 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录