【问题标题】:Flutter : Dart global variable is output as nullFlutter:Dart 全局变量输出为 null
【发布时间】:2022-11-14 02:53:50
【问题描述】:

如果formattedDate被声明为全局变量,并且在startScreenRecord中输出formattedDate,则输出良好。但是,如果在 stopScreenRecord 中再次输出formattedDate,则输出为空。我该如何解决这个问题?

    class _HomePageState extends State<HomePage> {
  var formattedDate;
  bool recording = false;
  var directory = Directory('/storage/emulated/0/DCIM/BackCamera').create(recursive: true);
  bool inProgress = false;

  Future<File> moveFile(File sourceFile, String newPath) async {
    try {

      return await sourceFile.rename(newPath);
    } on FileSystemException catch (e) {
      final newFile = await sourceFile.copy(newPath);
      await sourceFile.delete();
      return newFile;
    }
  }

  startScreenRecord(bool audio, String formattedDate) async {
    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;
  }
  stopScreenRecord() async {
    String path = await FlutterScreenRecording.stopRecordScreen;
    setState(() {
      recording = !recording;
    });
    print("Opening video");
    print(path);
    final directory = await getTemporaryDirectory();
    print(directory.path);
    // Move Title.mp4 to Download folder
    final newPath = '/storage/emulated/0/DCIM/' + "$formattedDate.mp4";
    print(formattedDate);
    print(newPath);
    print(formattedDate.toString());
    final file = await moveFile(File(path), newPath);
    print(file.path);
  }

【问题讨论】:

    标签: flutter dart global-variables


    【解决方案1】:

    这是因为您的代码中有两个同名formattedDate 的不同变量。让我解释:

    1. var formattedDate; - 你的_HomePageStateclass 的实例变量,可以通过this.formattedDate 引用。

    2. 有函数startScreenRecord(bool audio, String formattedDate) 及其参数。所以在函数体内,formattedDatethis.formattedDate 都有,但它们是不同的!

      当你在写作

      var formatter = new DateFormat('yyyy_MM_dd_HH_mm_ss');
      formattedDate = formatter.format(now);
      

      在函数体内,您实际上是在修改作为参数传递给函数的变量。您没有修改实例变量。 你需要做的是

      var formatter = new DateFormat('yyyy_MM_dd_HH_mm_ss');
      this.formattedDate = formatter.format(now);
      

    【讨论】:

      【解决方案2】:

      看起来像全局的从未使用过。 startScreenRecord 生成自己的日期。

      stopScreenRecord 无权访问类变量。

      如果我正确阅读了代码。您的功能在类之外。所以他们无法访问类变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-30
        • 2023-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多