future_data_handler.dart 1.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter_driver/driver_extension.dart';

typedef DriverHandler = Future<String> Function();

/// Wraps a flutter driver [DataHandler] with one that waits until a delegate is set.
///
/// This allows the driver test to call [FlutterDriver.requestData] before the handler was
/// set by the app in which case the requestData call will only complete once the app is ready
/// for it.
class FutureDataHandler {
  final Map<String, Completer<DriverHandler>> _handlers = <String, Completer<DriverHandler>>{};

  /// Registers a lazy handler that will be invoked on the next message from the driver.
  Completer<DriverHandler> registerHandler(String key) {
    _handlers[key] = Completer<DriverHandler>();
22
    return _handlers[key]!;
23 24
  }

25
  Future<String> handleMessage(String? message) async {
26 27 28 29
    if (_handlers[message] == null) {
      return 'Unsupported driver message: $message.\n'
             'Supported messages are: ${_handlers.keys}.';
    }
30
    final DriverHandler handler = await _handlers[message]!.future;
31 32 33 34 35
    return handler();
  }
}

FutureDataHandler driverDataHandler = FutureDataHandler();