[英]Instance of future void - flutter
I try to make it show the translation but it doesn't work:(我试图让它显示翻译,但它不起作用:(
I am new to this and appreciate your help, I know almost nothing about flutter.我是新手,感谢您的帮助,我对 flutter 几乎一无所知。
Widget build(BuildContext context) {
final translator = GoogleTranslator();
final input = summary;
// Using the Future API
var translation = translator
.translate(input, to: 'es')
.then((result) => print("Source: $input\nTranslated: $result"));
return Column(
children: [
const SectionTitle(title: "Información"),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, bottom: 20),
child: Text(("$translation"),
textAlign: TextAlign.justify,
style: TextStyle(
color: Colors.white.withOpacity(0.55),
fontSize: 15,
fontWeight: FontWeight.w400)),
),
],
);
} }
You shouldn't put those types of operations in the build
method as that could be run 60 times per second (actually even more).您不应该将这些类型的操作放在
build
方法中,因为它可以每秒运行 60 次(实际上甚至更多)。
Read a bit about FutureBuilder
(and StatefulWidget
) to get a feeling for where you could put the translator
and where you could call the translate()
method.阅读一些关于
FutureBuilder
(和StatefulWidget
)的内容,以了解可以将translator
放在哪里以及可以在哪里调用translate()
方法。
The example in the link call a future that is put into the variable _calculation
, consider that being the result of your translate()
method.链接中的示例调用了放入变量
_calculation
中的未来,认为这是您的translate()
方法的结果。
Try this:尝试这个:
class _MyWidgetState extends State<MyWidget>{
final translator = GoogleTranslator();
final input = summary;
String translation = ""; // assuming result is a string
bool _isLoading = true;
@override
iniState(){
super.initState();
_getTranslation();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
const SectionTitle(title: "Información"),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, bottom: 20),
child: _isLoading? Center(child:CircularProgressIndicator()): Text((translation),
textAlign: TextAlign.justify,
style: TextStyle(
color: Colors.white.withOpacity(0.55),
fontSize: 15,
fontWeight: FontWeight.w400)),),
//Bonus
TextButton(child:Text("Get translation"),onPressed:()async {
await _getTranslation();
}),
],
);
}
_getTranslation() async {
setIsLoading(true);
// Using the Future API
try{
translator
.translate(input, to: 'es')
.then((result) {
setTranslation(result);
setIsLoading(false);
}).timeout(Duration(seconds:10));
}on TimeoutException catch(_){
setIsLoading(false);
}catch(_){
setIsLoading(false);
}
}
setTranslation(String value){
setState(()=> translation = value);
}
setIsLoading(bool value){
setState(()=> _isLoading = value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.