i got this problem : the argument type 'Future' can't be assigned to the parameter type 'String'? , when i write this "Text(text.translate(to: 'es').toString())" i add .toString() it works in function translate() but i need it to work inside my build

class _TranslateState extends State<Translate> {
  GoogleTranslator translator = GoogleTranslator();
  String text = 'Hello , my name is Mehdi';
  void translate() {
    translator.translate(text, to: 'ru').then((output) {
      setState(() {
        text = output.toString();//it works here and give me the translate
      });
    });
  }

  @override
  Widget build(BuildContext context) return Container(
      child: Text(text.translate(to: 'es').toString())//but here doesn't work, it give me that error : the argument type 'Future<Translation>' can't be assigned to the parameter type 'String',
    );
  }
}

help

1

There are 1 best solutions below

0
On BEST ANSWER

Because the function translate is async, you need to await for the result. You can user for example Future builder like this:

class _TranslateState extends State<Translate> {
  GoogleTranslator translator = GoogleTranslator();
  String text = 'Hello , my name is Mehdi';
  Future<String> translate(String translateText) async {
    var result = await translator.translate(translateText, to: 'ru');
    return result.toString();
  }

  @override
  Widget build(BuildContext context) 
    return Container(
      child: FutureBuilder(
      future: translate(text),
          builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Text(snapshot.data);
          } else {
            return Text("Translating...");
          }
    });
  }
}