如何从正在侦听飞镖中某些流的函数返回字符串? [英] how to return a string from a function which is listening some stream in dart?

查看:66
本文介绍了如何从正在侦听飞镖中某些流的函数返回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为foo的函数,它正在侦听stdout,我要返回的是从stdout获得的一些字符串。这是我的功能;

i have a function called foo which is listening to the stdout, what i want is to return some string which i got from stdout. here is my function;

    dynamic foo(process) {
  return (
    process.stdout.transform(UTF8.decoder).listen((data) {
    String s = data.toString();
    // print(s);
    if (s.contains("received event of")) {
      var s1 = s.split(":");

      print("${s1[1]}");
      return s1[1];
    }
  }));
}

我想将s1返回给调用函数

I want to return s1 to the calling function

推荐答案

这应该做您想要的

Future<String> dynamic foo(process) {
  return process.stdout.transform(UTF8.decoder).map((data) {
    String s = data.toString();
    // print(s);
    if (s.contains("received event of")) {
      var s1 = s.split(":");

      print("${s1[1]}");
      return s1[1];
    } else {
      return null;
    }
  }).where((val) => val != null).first;
}

您的自定义代码返回有效值或 null
我将监听更改为 map 以便能够使用其他流方法。
其中过滤无效值( null )并返回第一个非- null 值。

Your custom code either returns a valid value or null. I changed listen to map to be able to use additional stream methods. where filters invalid values (null) and returns the first non-null value.

foo 方法的调用者需要处理返回的未来(例如使用 async / await )来获取值

The caller of the foo method needs to handle the returned Future (using for example async/await) to get the value when it becomes available.

使用它像

bar() async {
  ...
  var input = await foo(proc);
  print(input);
}

这篇关于如何从正在侦听飞镖中某些流的函数返回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆