You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现带onTap的可复用自定义Widget及GetX路由报错处理

Flutter自定义Widget调用GetX路由报错修复方案

错误原因

  • 参数类型不匹配:CardCity第三个入参要求是VoidCallback函数类型,原调用语句直接执行Get.to(() => const Manila()),返回的是Future对象,不是函数类型,触发类型不匹配报错
  • 语法错误:调用语句中第三个参数后多写了多余分号,导致括号匹配失败
  • 回调执行异常:原CardCity中InkWell的onTap回调仅声明了_onTap变量未调用,点击不会触发路由跳转,你提供的修复版中onTap: _onTap;后多写了分号,属于语法错误需要删除

修复代码

city.dart调用代码

CardCity('Manila', 'assets/images/manila.jpg', () => Get.to(() => const Manila()))

修正后的card_city.dart代码

import 'package:flutter/material.dart';
import 'package:sample/component/colors.dart';
import 'package:sample/component/styles.dart';

class CardCity extends StatelessWidget {
  final String _cityTitle;
  final String _cityAssetImage;
  final VoidCallback _onTap;

  const CardCity(this._cityTitle, this._cityAssetImage, this._onTap, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 150.0,
      decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(_cityAssetImage),
            fit: BoxFit.cover,
            colorFilter:
                const ColorFilter.mode(Color(0x400B7A77), BlendMode.srcOver),
          ),
          borderRadius: BorderRadius.circular(15)),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _onTap,
          borderRadius: BorderRadius.circular(15.0),
          splashColor: BrandColor.color.transNeon,
          child: Center(
            child: Text(
              _cityTitle.toUpperCase(),
              style: mainTitleBarabaraWhite,
            ),
          ),
        ),
      ),
    );
  }
}

说明

修改后入参为函数类型符合CardCity的类型要求,多余符号已清除,三个报错会全部解决,点击卡片即可正常触发路由跳转。

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:36:03