Flutter中全局变量formattedDate在stopScreenRecord输出null的解决方法
解决Flutter中全局变量formattedDate在stopScreenRecord中为null的问题
问题根源很明确:你在startScreenRecord方法里把formattedDate声明成了方法参数,这导致方法内部操作的是局部变量,而非类的全局变量。全局变量始终未被赋值,所以stopScreenRecord调用时自然返回null。
解决步骤
- 删掉
startScreenRecord方法的String formattedDate参数,让方法内部的formattedDate指向类的全局变量 - 直接给全局变量赋值,无需额外声明
修改后的关键代码
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
相关产品推荐
相关产品推荐

