Flutter compute method freeze the UI

Viewed 2246

init

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

state class :

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;
  }

here the writer used ++i instead of 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'),
     ]),
      ),

    );

  }
}

I have this code found on the net, for tutorial using async compute to make flutter works easier, but the code freeze when I clicked the button.. why ?

the writer add static int on the getinth function but doing so resulting in error compile. so I remove the static keywords

the isPrime like the name suggest should be to check wether a number is PrimeNumbers.

Does it has anything to do with phone models or android version ?? Ive installed the released apped in a 3GB phone

1 Answers

getnthPrime (the function passed to compute(...) needs to be a top-level function.
It must be declared outside of a class.

Related