0

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;
}
Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40
bach
  • 33
  • 4
  • how did you try to access the value returned from the function? – X 2 Sep 15 '21 at 11:30
  • ' var result = arabicBuyer.translate("sentence"); print(result.toString()); ' @X2 – bach Sep 17 '21 at 12:04
  • translate returns a Future so you will need to wait for the result. Either use await keyword like this var result = await arabicBuyer.translate("sentence"); or use .then like so arabicBuyer.translate("sentence").then((result) => print(result)); – X 2 Sep 17 '21 at 13:07
  • thanks. this resolved my issue. – bach Sep 17 '21 at 13:20

1 Answers1

0

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;
}
aytunch
  • 1,326
  • 1
  • 16
  • 31
  • The scope that you mentioned seems not right at least doesn't fit to my code. I get same error except . – bach Sep 17 '21 at 12:03