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

Flutter中全局变量formattedDate在stopScreenRecord输出null的解决方法

解决Flutter中全局变量formattedDate在stopScreenRecord中为null的问题

问题根源很明确:你在startScreenRecord方法里把formattedDate声明成了方法参数,这导致方法内部操作的是局部变量,而非类的全局变量。全局变量始终未被赋值,所以stopScreenRecord调用时自然返回null。

解决步骤

  1. 删掉startScreenRecord方法的String formattedDate参数,让方法内部的formattedDate指向类的全局变量
  2. 直接给全局变量赋值,无需额外声明

修改后的关键代码

startScreenRecord(bool audio) async { // 移除了String formattedDate参数
  bool start = false;

  var now = new DateTime.now();
  var formatter = new DateFormat('yyyy_MM_dd_HH_mm_ss');
  formattedDate = formatter.format(now); // 现在赋值的是类的全局变量
  print('-------------');
  print(formattedDate);
  print('-------------');
  if (audio) {
    start = await FlutterScreenRecording.startRecordScreenAndAudio(formattedDate);
  } else {
    start = await FlutterScreenRecording.startRecordScreen(formattedDate);
  }
  if (start) {
    setState(() => recording = !recording);
  }
  return start;
}

同时注意:调用startScreenRecord的地方也要对应去掉第二个参数,比如原调用startScreenRecord(true, xxx)需改为startScreenRecord(true)。

这样修改后,全局变量formattedDate会被正确赋值,stopScreenRecord方法就能正常获取到它的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:35:23