Home > OS >  Instance of future void - flutter
Instance of future void - flutter

Time:09-01

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.

 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)),
    ),
  ],
);

}

CodePudding user response:

You shouldn't put those types of operations in the build method as that could be run 60 times per second (actually even more).

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.

The example in the link call a future that is put into the variable _calculation, consider that being the result of your translate() method.

CodePudding user response:

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);
 }
}
  • Related