【问题标题】:How to return a string from a Future<String> in Flutter如何从 Flutter 中的 Future<String> 返回字符串
【发布时间】:2020-10-22 19:37:44
【问题描述】:

这是我一直在尝试的代码。我想使用extractInfo() 方法返回String

我们如何返回String,因为参数不接受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,
          ),`
        );
      }

【问题讨论】:

    标签: flutter dart translation


    【解决方案1】:

    你不能。您将需要像在第一种方法中一样使用async/await。由于您的控件不接受Future&lt;String&gt;,因此您需要将其包装在FutureBuilder 中。你可以看到如何做到这一点here

    【讨论】:

    • 如果我要使用未来的 builder,我将无法使用故事项目,请在这里帮助我
    • 为什么不呢?我不知道如何帮助你,没有更好的问题描述。
    • 我们想在 Instagram 故事中展示我们的数据。我们正在翻译从 api 收到的数据。一切正常,但我们无法显示这些翻译后的数据
    • 所以,创建一个函数来翻译数据,因为它会返回一个Future&lt;YourData&gt;,你需要一个FutureBuilder 来正确构建你的用户界面。
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2021-02-06
    • 2021-03-07
    • 1970-01-01
    • 2021-04-28
    • 2021-10-07
    相关资源
    最近更新 更多