gpt4 book ai didi

asynchronous - Flutter 计算方法卡住 UI

转载 作者:IT王子 更新时间:2023-10-29 07:05:45 24 4
gpt4 key购买 nike

初始化

 class MyHomePage extends StatefulWidget{
@override
_MyHomePageState createState() => _MyHomePageState();
}

状态类:

class _MyHomePageState extends State<MyHomePage> {
int prime;


bool isPrime(int n) {
int count = 0;
for(int i = 1 ; i <= n; ++i) {
if (n % i == 0) {
++count;
}
}
return count == 2;
}

这里作者用了++i而不是i++

  /// Returns the nth prime number.
int getnthPrime(int n) {
int currentPrimeCount = 0;
int candidate = 1;
while(currentPrimeCount < n) {
++candidate;
if (isPrime(candidate)) {
++currentPrimeCount;
} }
return candidate;

}

void _getPrime() async {
int ans = await compute(getnthPrime,10);
setState((){
prime=ans;
});
}


@override
Widget build(BuildContext context) {

return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Basic AppBar'),
),
body: Column(
children: <Widget> [
Padding(
padding: const EdgeInsets.all(16.0),
child: RaisedButton(child:Text('GEN'), onPressed: _getPrime,)

),
Text('result : $prime'),
]),
),

);

}
}

我在网上找到了这段代码,用于使用异步计算使 flutter 工作更容易的教程,但是当我单击按钮时代码卡住了。为什么?

作者在 getinth 函数上添加了 static int,但这样做会导致编译错误。所以我删除了静态关键字

isPrime 顾名思义应该是检查一个数是否为 PrimeNumbers。

跟手机型号和安卓版本有关系吗??我在 3GB 手机中安装了发布的应用程序

最佳答案

getnthPrime(传递给compute(...)的函数需要是顶层函数。
它必须在类之外声明。

关于asynchronous - Flutter 计算方法卡住 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53187523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com