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

学习GetX与Flutter时遇官方示例报错:RxInt不是(() => void)?的子类型

GetX + Flutter 类型错误问题解决

报错信息

The following _TypeError was thrown building Home(dirty): type 'RxInt' is not a subtype of type '(() => void)?'

问题根源

错误出在FloatingActionButton的onPressed参数上:

floatingActionButton: FloatingActionButton(
    onPressed: c.increment(), child: const Icon(Icons.add)),

这里直接调用c.increment()会立即执行方法,而increment()返回的是count++的结果(RxInt类型),但onPressed要求传入的是无参函数引用(() => void),不是函数执行后的返回值。

另外还有一个小问题:AppBar的文本里多了一个多余的左大括号,会导致显示异常。

修正方案

  1. 把onPressed: c.increment()改成onPressed: c.increment,传递函数引用而非执行函数;
  2. 修正AppBar文本的语法错误。

修正后完整代码

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() => runApp(
      const GetMaterialApp(
        home: Home(),
      ),
    );

class Controller extends GetxController {
  var count = 0.obs;
  increment() => count++;
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Controller c = Get.put(Controller());

    return Scaffold(
      appBar: AppBar(
        title: Obx(
          () => Text('Taps: ${c.count}'),
        ),
      ),
      body: Center(
          child: ElevatedButton(
              onPressed: () => Get.to(Other()),
              child: const Text('Go to others'))),
      floatingActionButton: FloatingActionButton(
          onPressed: c.increment,
          child: const Icon(Icons.add)),
    );
  }
}

class Other extends StatelessWidget {
  final Controller c = Get.find();

  Other({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('${c.count}'),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:24:22