Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple arguments to the compute function in Flutter

Tags:

flutter

dart

I was trying to use the compute function in Flutter.

void _blockPressHandler(int row, int col) async {
//    Called when user clicks any block on the sudoku board . row and col are the corresponding row and col values ;
    setState(() {
      widget.selCol = col;
      }
    });

    bool boardSolvable;
    boardSolvable = await compute(SudokuAlgorithm.isBoardInSudoku , widget.board , widget.size) ;

  }

isBoardInSudoku is a static method of class SudokuAlgorithm. Its present in another file. Writing the above code , tells me that

error: The argument type '(List<List<int>>, int) → bool' can't be assigned to the parameter type '(List<List<int>>) → bool'. (argument_type_not_assignable at [just_sudoku] lib/sudoku/SudokuPage.dart:161)

How do i fix this? Can it be done without bringing the SudokuAlgorithm class's methods out of its file ? How to send multiple arguments to the compute function ?

static bool isBoardInSudoku(List<List<int>>board , int size ){ } is my isBoardInSudoku function.

like image 864
Natesh bhat Avatar asked Jan 07 '19 12:01

Natesh bhat


People also ask

How do you pass arguments in Navigator pushNamed?

You can accomplish this task using the arguments parameter of the Navigator. pushNamed() method. Extract the arguments using the ModalRoute. of method or inside an onGenerateRoute() function provided to the MaterialApp or CupertinoApp constructor.

How do you compute in flutter?

Compute function takes two parameters : A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level). Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).


2 Answers

Just put the arguments in a Map and pass that instead.

There is no way to pass more than one argument to compute because it is a convenience function to start isolates which also don't allow anything but a single argument.

like image 142
Günter Zöchbauer Avatar answered Sep 19 '22 04:09

Günter Zöchbauer


Use a map. Here is an example:

Map map = Map();
map['val1'] = val1;
map['val2'] = val2;
Future future1 = compute(longOp, map);


Future<double> longOp(map) async {
  var val1 = map['val1'];
  var val2 = map['val2'];
   ...
}
like image 32
live-love Avatar answered Sep 17 '22 04:09

live-love