Home > OS >  Using async function inside non async function in flutter
Using async function inside non async function in flutter

Time:09-15

i have a question,

I have a custom class, which has a constructor. One of the parameters of the constructor is a function. so i call it like this: TableWidget(table_number: "Table 1", iconcolor: getColor("Table 1", _DateSelectTable.getvalue())),. The getColor function is not async, but inside that function i want to open a file using path provider, which is async. How can i make this work without getting errors?

Thanks a lot

*Edit: added the getColor function code:

getColor(tableNumber, date) {
  final File file = File('assets/states1.txt');
  lines = file.readAsLinesSync(encoding: utf8);
  for(var line in lines){
    if(line.substring(0, 7) == tableNumber){
      if(line.substring(13, 15) == "${date.day}"){
        return Colors.red;
      }
    }
  }
  return Colors.black;
}

What i want to do here and the reason why i am asking you is that instead of have the path to the file as 'assets/states1.txt' i want to use the get documents directory function, which is async. thank you.

CodePudding user response:

so I let's put this as example because you didn't put that getColor function

getColor(...) {
    // your normal function 
  }

what I understand is that you want to call an asynchronous function insidz of it, let's say getFile(), you can put it like this

 getColor(...) async {
    // your normal function 

    await getFile();
  }

you can add the async keyword to your function and it will work normally, and you can put inside of it an asynchronous function that will until it will be done.

CodePudding user response:

try this

Future<Color> getColor(tableNumber, date) async{
  Directory tempDir = await getTemporaryDirectory();
  final File file =   File(tempDir.path);
  lines = file.readAsLinesSync(encoding: utf8);
  for(var line in lines){
    if(line.substring(0, 7) == tableNumber){
      if(line.substring(13, 15) == "${date.day}"){`enter code here`
        return Colors.red;
      }
    }
  }
  return Colors.black;
}
  • Related