当我尝试使用类未来的future.sync时
import 'package:async/async.dart';
import 'dart:async';
void main() {
var fur3 = new Future<int>(() => 45);
int z = Future.sync(fur3);
print(z);
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误消息
打破异常:NoSuchMethodError类型的对象
我是否以错误的方式使用future.sync?
我的第二个问题是
import 'package:async/async.dart';
void main() {
var fur1 = new Future<int>(() => 45);
fur1.then((value) {
return value;
}).catchError((err) => print('catchError1: ${err}'));
}
Run Code Online (Sandbox Code Playgroud)
为什么当我尝试从包中导入异步库时,我有编译器消息
打破异常:TypeError类型的对象
未定义类'Future'
我在这做错了什么?
所以基本上我有这段工作代码:
List<User> users = List();
await Future.forEach(querySnapshot.documents, (doc) async {
final snapshot = await doc['user'].get();
users.add(User(id: snapshot["id"], name: snapshot["mail"]));
});
return users;
Run Code Online (Sandbox Code Playgroud)
它可以正常工作,并且完全满足我的需求,但是我想知道是否有办法将其更改为地图,例如:
return querySnapshot.documents.map((doc) async {
final snapshot = await doc['user'].get();
User(id: snapshot["id"], name: snapshot["mail"]);
}).toList{growable: true};
Run Code Online (Sandbox Code Playgroud)
我这样做的问题是它说:无法将List <Future <Null >>类型的值赋给List <User>类型的变量。
所以我想知道是否有可能或唯一的方法是使用Future.forEach
如何从 Future 对象返回 Future 值?这段代码不起作用。
import 'dart:async';
void main() {
var temp = foo();
temp.then((Future<int> future) {
future.then((int result) {
print(result);
});
});
}
Future<Future<int>> foo() {
return new Future<Future<int>>(() {
return new Future<int>(() => 5);
});
}
Run Code Online (Sandbox Code Playgroud)
如何避免不必要的拆包?
在这种情况下,在异步库“Future”中声明为通用类。
abstract class Future<T> {
}
Run Code Online (Sandbox Code Playgroud)
如果我创建如下表达式
new Future<Future<int>>();
Run Code Online (Sandbox Code Playgroud)
然后将类型T 指定为Future<int>泛型类 Future 预期的结果?
我认为结果必须与 type argument 中指定的相同T。
IEFuture<int>.
但结果并不如预期。在 Dart API 网站上没有找到有关此异常行为的信息。
如果这是一个“功能”(但我认为异常行为错误地称为“功能”)那么为什么它没有记录在 Dart API 中?
如何解释这种差异?
为什么这段代码没有生成错误和警告?
另一个相同的例子,但没有使用 Future。
void main() {
var temp …Run Code Online (Sandbox Code Playgroud) 简而言之,简单的代码片段,Futures(dart)或Promises(js)似乎为回调的恐怖提供了一个模糊有用的解决方案.
使用大型软件时会出现问题,例如,您正在与之交谈的服务器开始返回垃圾邮件,从而触发一个深埋在第三方代码中的迄今未见过的异常.此时,在一个令人难以置信的长链.then的某个地方,以catchError结束,你将成为新的"空指针异常"之类的幸运接收者.它从哪里来的?谁知道?显然,我们并没有使用这些技术神奇地获取调用堆栈,并且没有任何使用的跟踪信息 - 在这个巨大的链中可能会调用50次特定函数,并且在某些任意调用时会引发错误.
面对这种情况时,最好采用哪些策略?
我想使用io示例尝试使用Dart的rpc包(https://github.com/dart-lang/rpc)
我在64位版本的Dart编辑器上使用1.9.1 sdk(无法更新更多稳定版本)
这是我的pubspec.yaml:
name: myDartRestServer
version: 0.0.1
description: A minimal command-line application.
#author: <your name> <email@example.com>
#homepage: https://www.example.com
environment:
sdk: '1.9.1'
dependencies:
rpc: any
dev_dependencies:
unittest: any
Run Code Online (Sandbox Code Playgroud)
但是当我尝试复制样本以启动我的服务器时:
final ApiServer _apiServer = new ApiServer('/api/', prettyPrint: true);
void start() {
_apiServer.addApi(new Synchro());
HttpServer server = await HttpServer.bind(InternetAddress.ANY_IP_V4, 9090);
server.listen(_apiServer.httpRequestHandler);
_apiServer.enableDiscoveryApi("http://localhost:9090");
}
Run Code Online (Sandbox Code Playgroud)
我的EDI(SDK)不知道await关键字.(我在我的库文件中导入了dart:io dart:async和rpc包)
我错过了什么?感谢您提前回复.祝你今天愉快.
嘿,我对Dart Futures还是陌生的,我有以下情况。
每当用户在UI中键入字母时,addressChanged()都会调用ui_component中的方法。此方法调用getProposals()我的地图componenet中的方法,该方法向google maps API发出异步请求。结果到这里后,我想将它们返回到UI组件,该组件将填充UI中的propasals下拉列表。
我陷入了最后一步:如何(以及最好的方法)将异步回调函数的结果返回给父组件(同时保留可重用的map组件?)。
这是我尝试过的:
1)UI_Component:
// I get called if a user typed a new letter
Future addressChanged(dynamic event) async {
String id = event.target.id;
String address = event.target.value;
if(id=="pickup") {
this.pickup = address;
} else if(id=="destination") {
this.destination = address;
}
// this is where I call the subcomponent and want to get the address propasals
String proposals = await googleMap.getProposals(address,id);
print(proposals);
populateProposalDropdown();
}
Run Code Online (Sandbox Code Playgroud)
2)Google Map组件:
Future getProposals(String address,String id) async { …Run Code Online (Sandbox Code Playgroud) 我想使用DecodeGifAnimation 解码带有图像包的gif ,但它需要太长时间并导致我的webapp冻结.该库似乎也没有任何异步方法.我查看了如何在Dart中进行异步处理,似乎我需要使用Futures,虽然我不知道如何为我的函数创建一个.
不太确定我在做什么
void decode(Uint8List data) {
Future anim = decodeGifAnimation(data); // but it returns Animation, not a Future!
anim.then(prepare);
}
Run Code Online (Sandbox Code Playgroud) 当我发现我必须从内部函数中返回外部函数值时,我在dart中编写了一个从浏览器端索引数据库中删除对象的函数:
Future<bool> delete() {
Transaction tx = db.transactionStore(storeName, "readwrite");
ObjectStore os = tx.objectStore(storeName);
os.delete(_key); // returns blank future, modifies tx
// This is not correct, but shows the idea:
if (tx.onComplete) {return true;}
if (tx.onError) {return false;}
}
Run Code Online (Sandbox Code Playgroud)
此函数是我用于保存和加载到索引数据库的类的方法.当删除操作成功或失败时,我希望此函数返回true或false包含相同的Future对象.但是,瓶颈是os.delete(_key);声明:它返回一个未来,但删除操作的实际成功或失败由tx.onComplete和提供tx.onError.这两个对象都是流,所以我需要创建处理来自它们的事件的匿名函数:
tx.onComplete.listen((e){
return_to_outer_function(true);
});
tx.onError.listen((e){
return_to_outer_function(false);
});
return_to_outer_function(bool) {
return bool; // doesn't work
}
Run Code Online (Sandbox Code Playgroud)
如您所见,当我创建匿名函数时,return语句不再完成方法,而是内部函数.我可以让内部函数调用其他函数,但那些其他函数有自己的return语句,它们不会将结果返回给整个方法.
我尝试了设置临时变量并定期检查它们的方法,但这是一个非常不优雅的解决方案,我不想使用,不仅仅是潜在的错误,而是因为它会占用单线程事件循环.
是否可以从内部函数返回值到外部函数?或者是否有其他更好的方法从一组流中存在或不存在事件中获取值?或者是否有另一种方法可以使用IndexedDB来避免这个问题?
我正在flutter中实现一个计时器。这是应用程序的结构。
页面A(包含一些列表,用户单击该列表并将其带到计时器页面)。Page B格式可以运行计时器。我能够正确运行计时器/秒表,但是当我按Page BI上的后退按钮时,会在处理错误后调用setstate()。我知道这是预期的行为。如果我在处理时使用timer.cancel(),则不会收到错误消息,但计时器将停止运行。即使我导航至页面A或说任何其他新页面(小部件),计时器/秒表也应继续运行。我知道可以使用侦听器和WidgetBindingObserver来实现,但是我不知道如何实现它。希望我会在此问题上获得一些帮助。
B页的构建类:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: new IconButton(icon: new Icon(Icons.arrow_back), onPressed: ()async{
Navigator.pop(context,widget._elapsedTime);
}),
title: Text("widget.title"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_elapsedTime'),
RaisedButton(
child: Text('Start'),
onPressed: () {
if(watch.isRunning){
stopWatch();
}
else{
startWatch();
}
},
),
],
),
));
Run Code Online (Sandbox Code Playgroud)
StartWatch功能:
startWatch() {
watch.start();
timer = new Timer.periodic(new Duration(milliseconds:1000), updateTime);}
Run Code Online (Sandbox Code Playgroud)
更新时间函数每秒调用一次:
updateTime(Timer timer) {
if (watch.isRunning) {
print(_elapsedTime);
var time= formatedTime(watch.elapsedMilliseconds);
print("time is"+time);
setState(() {
_elapsedTime = time; …Run Code Online (Sandbox Code Playgroud) Dart 新手,我目前正在学习 Dart 中的异步执行。我对 Dart 中的并发性如何工作感到有些恼火,从他们的代码实验室中获取以下场景:
void printOrderMessage () async {
try {
var order = await fetchUserOrder();
print('Awaiting user order...');
print(order);
} catch (err) {
print('Caught error: $err');
}
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex.
var str = Future.delayed(Duration(seconds: 4), () => throw 'Cannot locate user order');
return str;
}
Future<void> main() async {
await printOrderMessage();
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,异步操作是从数据库中获取用户订单。现在因为 Dart 的 await/async 机制,每个与异步操作相关的函数都需要有Future<>返回类型,并且必须用async.
这感觉很笨重......想象一下,如果我的函数链深处的某个值被异步计算,我真的需要总是返回一个未来吗?除了等待之外,还有其他结构可以同步 Dart 中的代码吗?还是我误解了这个概念?
类似于这个 Flutter question我想嵌套 Streams。
在 Flutter 中,这可以通过嵌套StreamBuilders轻松实现,但是,我不想使用小部件。相反,我想单独在Dart 中解决问题。(这里的嵌套意味着一个流依赖于另一个流的值,这些值应该组合在一起)
让我来说明这个问题:
Stream streamB(String a);
streamA: 'Hi' --- 'Hello' ---- 'Hey'
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我有一个streamA连续发射事件和streamB该出现从该事件streamA发出。在streamC,我要要更新每一个事件的streamB。
如果我有valueB而不是streamB,我可以简单地使用streamA.map((event) => valueB(event)),但是,Stream.map只能处理同步值。
还有Stream.asyncMap,但是,只适用于Future秒。
然后,有还 Stream.expand,但仅适用于同步iterables。
早些时候,我是一个javascript程序员,我使用来自caolan的库异步来防止回调地狱异步库.
在这些日子里,我转向飞镖,异步风格几乎与javascript一样.我真的很喜欢async.waterfall函数,我可以按顺序执行回调函数.
我怎么能用飞镖做到这一点?他们有一个类似的飞镖库吗?
我目前正在从蓝牙设备读取变量。这显然需要不确定的时间,所以我使用期货(这个方法在下面的代码中是 readCharacteristic )。
一次不能进行多个读取操作——如果在第一个操作仍在进行时启动了第二个读取操作,Flutter 将抛出错误。
我的理解是,使用 .then() 将期货链接在一起只会允许在前一个调用完成时执行下一个语句。这个想法似乎是正确的,直到我尝试读取第三个值——也就是当错误被抛出时,因为重叠的读取事件。
这是我的代码:
readCharacteristic(scanDurationCharacteristic)
.then((list) => sensorScanDuration = list[0].toDouble())
.then((_) {
readCharacteristic(scanPeriodCharacteristic)
.then((list) => sensorScanPeriod = list[0].toDouble());
}).then((_) {
readCharacteristic(aggregateCharacteristic)
.then((list) => sensorAggregateCount = list[0].toDouble());
}).then((_) {
readCharacteristic(appEUICharacteristic)
.then((list) => appEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(devEUICharacteristic)
.then((list) => devEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(appKeyCharacteristic)
.then((list) => appKey = decimalToHexString(list));
});
Run Code Online (Sandbox Code Playgroud)
确保这些读取事件不会重叠的更好方法是什么?
dart ×13
dart-async ×13
flutter ×3
asynchronous ×2
android ×1
async-await ×1
dart-io ×1
dart-rpc ×1
dart-sdk ×1
foreach ×1
future ×1
indexeddb ×1
promise ×1