【问题标题】:Function hangs UI函数挂起 UI
【发布时间】:2020-01-08 15:02:50
【问题描述】:

我正在使用 Dart、AndroidStudio、Flutter

我需要调用一个函数来散列我的密码。哈希函数需要时间来执行。代码应该在印刷机上运行。功能是:

String getHash(Stirng input)

我称之为:

onPressed:{
           newPass=getHash(currentPass);
          }

它阻塞了 UI 线程。该函数来自某些 API,因此无法编辑。

我创建了一个async 方法并在async 函数中调用了getHash()

Future<String> asyncMethodToGetHash(String input) async{
     return await geHash(input);
}

但它仍然会阻塞 UI 线程。我应该如何调用它,以便 UI 不被阻塞?

【问题讨论】:

    标签: android api flutter


    【解决方案1】:

    您可以使用颤振提供的compute() 方法,该方法将在单独的隔离中运行代码(相当于线程的飞镖)。像这样的:

    static String getHash(String input){
         return hash(input); // your code to calculate hash here.
    }
    
    String computeHash(String input){
         return await compute(getHash, input);
    }
    

    请记住,您传递给compute() 方法的函数必须是静态的,并且只能接受一个参数。由于隔离不共享内存,因此函数中使用的每个变量都必须作为参数传递。因此,如果您必须将多个方法传递给函数,则必须制作一个参数列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2019-07-08
      • 2011-02-06
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多