Instance of '_Future<dynamic>' instead of input value in Translator package from Flutter

194 Views Asked by At

this scope gives me Instance of _Future but I want to get that translated text.

Future<dynamic> translate(String input) async {
final translator = GoogleTranslator();
var result;
var translation = await translator
    .translate(input, to: 'tr')
    .then((value) => {result = value});
  return result;
}
1

There are 1 best solutions below

1
On

Does this work? I guess the .translate function returns an Translate instance. You need the text attribute to get a String

Below code is wrong!

Future<String> translate(String input) async {
  final translator = GoogleTranslator();
  var result;
  var translation = await translator
      .translate(input, to: 'tr')
      .then((value) => {result = value});
  return result.text;
}

Also you use a then clause and getting the result of translation in to value so you don't need to use await and set the var translation in this case. Or you can use await and remove the then. But you should not use both await and then for the same async method.

So the below code should be used:

Future<String> translate(String input) async {
  final translator = GoogleTranslator();
  var translation = await translator
      .translate(input, to: 'tr');
  return translation.text;
}