[英]Instance of future void - 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)),
),
],
);
}
您不應該將這些類型的操作放在build
方法中,因為它可以每秒運行 60 次(實際上甚至更多)。
閱讀一些關於FutureBuilder
(和StatefulWidget
)的內容,以了解可以將translator
放在哪里以及可以在哪里調用translate()
方法。
鏈接中的示例調用了放入變量_calculation
中的未來,認為這是您的translate()
方法的結果。
嘗試這個:
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.