Flutter with Translator:为什么不能将参数类型 'Future<Translation>' 分配给参数类型 'String'?
Flutter with Translator : why the argument type 'Future<Translation>' can't be assigned to the parameter type 'String'?
我遇到了这个问题:参数类型 'Future' 不能分配给参数类型 'String'? ,当我写这个“Text(text.translate(to: 'es').toString())”
我添加 .toString() 它在函数 translate() 中工作,但我需要它在我的 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',
);
}
}
帮助
因为翻译函数是异步的,所以需要等待结果。例如,您可以像这样使用 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...");
}
});
}
}
我遇到了这个问题:参数类型 'Future' 不能分配给参数类型 'String'? ,当我写这个“Text(text.translate(to: 'es').toString())” 我添加 .toString() 它在函数 translate() 中工作,但我需要它在我的 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',
);
}
}
帮助
因为翻译函数是异步的,所以需要等待结果。例如,您可以像这样使用 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...");
}
});
}
}