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

Flutter调用rannn方法显示Closure而非随机任务文本该如何修复?

问题原因与修复方案

核心问题点

  • 你在Text组件中直接写了Provider.of<TaskData>(context).rannn,没有加括号执行函数,导致直接输出了函数对象的Closure描述文本
  • rannn方法定义错误:返回值声明为void,无法拿到返回的随机任务名;存在多余的无名称String参数;加了async关键字但没有返回Future类型,和后续你用FutureBuilder调用的逻辑不匹配
  • 后续FutureBuilder中调用的方法名是rann(),和实际定义的rannn()名称不一致,属于拼写错误

修复步骤

第一步:修正TaskData中的rannn方法

class TaskData extends ChangeNotifier {
  List<Task> _tasks = [
    Task(name: "Task one"),
    Task(name: "Task two"),
    Task(name: "Task three"),
  ];
  UnmodifiableListView<Task> get tasks {
    return UnmodifiableListView(_tasks);
  }
  // 修正方法:去掉多余参数,修改返回值类型为Future<String>适配FutureBuilder场景
  Future<String> rannn() async {
    var randomItem = (_tasks.toList()..shuffle()).first.name;
    print(randomItem);
    // 如果需要状态更新就打开下面注释
    //notifyListeners();
    return randomItem;
  }
}

第二步:修正页面中的调用逻辑

如果是直接在Text中展示,不需要FutureBuilder的话写法如下:

// 方法后加括号执行,拿到返回值拼接字符串
Text(
  "${Provider.of<TaskData>(context).rannn()} Tasks",
),

如果是配合你现有的FutureBuilder使用,需要修正方法名拼写,同时增加加载态判断避免空值显示:

FutureBuilder(
  // 修正方法名拼写为rannn,加括号执行
  future: Provider.of<TaskData>(context).rannn(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
      return Text(
        "${snapshot.data} Tasks",
        style: TextStyle(
            color: Colors.white,
            fontSize: 35,
            fontWeight: FontWeight.w700),
      );
    }
    return const CircularProgressIndicator(color: Colors.white);
  },
),

补充优化:stopTimer方法逻辑修正

你现有的stopTimer判断逻辑if (reset == mounted)存在逻辑错误,建议修正为:

void stopTimer({bool reset = true}) {
  setState(() => timer?.cancel());
  if (reset && mounted) {
    resetTimer();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:27:03