1

我遇到了这个问题:参数类型“Future”不能分配给参数类型“String”?,当我写这个“Text(text.translate(to:'es').toString())”时,我添加了.toString()它在函数translate()中工作,但我需要它在我的构建中工作

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',
    );
  }
}

帮助

4

1 回答 1

0

因为函数 translate 是异步的,所以您需要等待结果。例如,您可以像这样使用 Future builder:

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...");
          }
    });
  }
}
于 2021-08-25T22:56:47.667 回答