简体   繁体   中英

How to return a string from a Future<String> in Flutter

This is the code I have been trying. I want to return a String using extractInfo() method.

How can we return a String because the parameter is not accepting any other argument than the String

      Future<String> info(String x) a sync{
        final translator = Google Translator();
        return await translator.translate(x, to: 'en');
      }
      String y;
      String extract Info(){
        String x = "Title :${widget.userPosts[widget.index].title}\n"
            "User Id :${widget.userPosts[widget.index].userId}\n"
            "Id :${widget.userPosts[widget.index].id}\n"
            "Completed :${widget.userPosts[widget.index].completed}\n";
    
        info(x).then((value) => y = value);
        print(y);
        return x;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("More"),
          ),
          body: StoryView(
            storyItems: [
              StoryItem.text(
                title: extractInfo(),
                backgroundColor: Colors.redAccent,
              )
            ],
            onStoryShow: (s) {
              print("Showing a story");
            },
            onComplete: () {
              print("Completed a cycle");
            },
            progressPosition: ProgressPosition.top,
            repeat: false,
            controller: story Controller,
          ),`
        );
      }

You cannot. You will need to use async / await like you did in the first method. Since your control does not accept a Future<String> you will need to wrap it in a FutureBuilder . You can see how to do that here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM