runZoned<R> function
- Rbody(), {
- Map<
Object?,Object?> ?zoneValues, - ZoneSpecification?zoneSpecification,
- @Deprecated("Use runZonedGuarded instead")Function?onError,
Runsbody in its own zone.
Creates a new zone usingZone.fork based onzoneSpecification andzoneValues, then runsbody in that zone and returns the result.
Example use:
var secret = "arglebargle"; // Or a random generated string.var result = runZoned( () async { await Future.delayed(Duration(seconds: 5), () { print("${Zone.current[#_secret]} glop glyf"); }); }, zoneValues: {#_secret: secret}, zoneSpecification: ZoneSpecification(print: (Zone self, parent, zone, String value) { if (value.contains(Zone.current[#_secret] as String)) { value = "--censored--"; } parent.print(zone, value); }));secret = ""; // Erase the evidence.await result; // Wait for asynchronous computation to complete.The new zone interceptsprint and stores a value under the privatesymbol#_secret. The secret is available from the newZone object,which is theZone.current for the body,and is also the first,self, parameter to theprint handler function.
If theZoneSpecification.handleUncaughtError is set, or the deprecatedonError callback is passed, the created zone will be anerror zone.Asynchronous errors in futures never cross zone boundaries between zoneswith a differentZone.errorZone.A consequence of that behavior can be that aFuture which completes as anerror in the created zone will seem to never complete when used from a zonethat belongs to a different error zone.Multiple attempts to use the future in a zone where the error isinaccessible will cause the error to be reportedagain in it's originalerror zone.
SeerunZonedGuarded in place of using the deprectedonError argument.IfonError is provided this function also tries to catch and handlesynchronous errors frombody, but may throw an error anyway returningnull if the generic argumentR is not nullable.
Implementation
R runZoned<R>( R body(), { Map<Object?, Object?>? zoneValues, ZoneSpecification? zoneSpecification, @Deprecated("Use runZonedGuarded instead") Function? onError,}) { if (onError != null) { // TODO: Remove this when code have been migrated off using [onError]. if (onError is! void Function(Object, StackTrace)) { if (onError is void Function(Object)) { var originalOnError = onError; onError = (Object error, StackTrace stack) => originalOnError(error); } else { throw ArgumentError.value( onError, "onError", "Must be Function(Object) or Function(Object, StackTrace)", ); } } return runZonedGuarded( body, onError, zoneSpecification: zoneSpecification, zoneValues: zoneValues, ) as R; } return _runZoned<R>(body, zoneValues, zoneSpecification);}