Is there a way to load async data on InitState method?

前端 未结 9 1548
你的背包
你的背包 2020-12-05 16:39

I\'m a looking for a way to load async data on InitState method, I need some data before build method runs. I\'m using a GoogleAuth code, and I need to execute build method

9条回答
  •  佛祖请我去吃肉
    2020-12-05 17:34

    I came here because I needed to fetch some files from FTP on program start. My project is a flutter desktop application. The main thread download the last file added to the FTP server, decrypts it and displays the encrypted content, this method is called from initState(). I wanted to have all the other files downloaded in background after the GUI shows up.

    None of the above mentioned methods worked. Constructing an Isolate is relatively complex.

    The easy way was to use the "compute" method:

    1. move the method downloading all files from the FTP out of the class.
    2. make it an int function with an int parameter (I do not use the int parameter or the result)
    3. call it from the initState() method

    In that way, the GUI shows and the program downloads the files in background.

      void initState() {
        super.initState();
        _retrieveFileList(); // this gets the first file and displays it
        compute(_backgroundDownloader, 0); // this gets all the other files so that they are available in the local directory
      }
    
    int _backgroundDownloader(int value) {
      var i = 0;
      new Directory('data').createSync();
      FTPClient ftpClient = FTPClient('www.guckguck.de',
          user: 'maxmusterman', pass: 'maxmusterpasswort');
      try {
        ftpClient.connect();
        var directoryContent = ftpClient.listDirectoryContent();
        // .. here, fileNames list is reconstructed from the directoryContent
    
        for (i = 0; i < fileNames.length; i++) {
          var dirName = "";
          if (Platform.isLinux)
            dirName = 'data/';
          else
            dirName = r'data\';
          var filePath = dirName + fileNames[i];
          var myDataFile = new File(filePath);
          if (!myDataFile.existsSync())
            ftpClient.downloadFile(fileNames[i], File(filePath));
        }
      } catch (err) {
        throw (err);
      } finally {
        ftpClient.disconnect();
      }
      return i;
    

提交回复
热议问题