boost_container.dart 11.2 KB
Newer Older
Jidong Chen's avatar
init  
Jidong Chen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2019 Alibaba Group
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
ColdPaleLight's avatar
ColdPaleLight committed
24 25
import 'dart:io';

Jidong Chen's avatar
init  
Jidong Chen committed
26
import 'package:flutter/material.dart';
shaode.lsd's avatar
fix:  
shaode.lsd committed
27
import 'package:flutter/services.dart';
Yacumima's avatar
dev  
Yacumima committed
28 29 30
import 'container_manager.dart';
import '../flutter_boost.dart';
import 'boost_page_route.dart';
31
import '../support/logger.dart';
Jidong Chen's avatar
init  
Jidong Chen committed
32 33 34 35

enum ContainerLifeCycle {
  Init,
  Appear,
36
  WillDisappear,
Jidong Chen's avatar
init  
Jidong Chen committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
  Disappear,
  Destroy,
  Background,
  Foreground
}

typedef void BoostContainerLifeCycleObserver(
    ContainerLifeCycle state, BoostContainerSettings settings);

class BoostContainer extends Navigator {
  final BoostContainerSettings settings;

  const BoostContainer(
      {GlobalKey<BoostContainerState> key,
      this.settings = const BoostContainerSettings(),
      String initialRoute,
      RouteFactory onGenerateRoute,
      RouteFactory onUnknownRoute,
      List<NavigatorObserver> observers})
      : super(
            key: key,
            initialRoute: initialRoute,
            onGenerateRoute: onGenerateRoute,
            onUnknownRoute: onUnknownRoute,
            observers: observers);

  factory BoostContainer.copy(Navigator navigator,
          [BoostContainerSettings settings = const BoostContainerSettings()]) =>
      BoostContainer(
        key: GlobalKey<BoostContainerState>(),
        settings: settings,
        initialRoute: navigator.initialRoute,
        onGenerateRoute: navigator.onGenerateRoute,
        onUnknownRoute: navigator.onUnknownRoute,
        observers: navigator.observers,
      );

  factory BoostContainer.obtain(
          Navigator navigator, BoostContainerSettings settings) =>
      BoostContainer(
          key: GlobalKey<BoostContainerState>(),
          settings: settings,
          onGenerateRoute: (RouteSettings routeSettings) {
            if (routeSettings.name == '/') {
              return BoostPageRoute<dynamic>(
                  pageName: settings.name,
                  params: settings.params,
                  uniqueId: settings.uniqueId,
                  animated: false,
                  settings: routeSettings,
                  builder: settings.builder);
            } else {
              return navigator.onGenerateRoute(routeSettings);
            }
          },
          observers: <NavigatorObserver>[
            ContainerNavigatorObserver.bindContainerManager()
          ],
          onUnknownRoute: navigator.onUnknownRoute);

  @override
  BoostContainerState createState() => BoostContainerState();

  @override
  StatefulElement createElement() => ContainerElement(this);

  static BoostContainerState tryOf(BuildContext context) {
    final BoostContainerState container =
        context.ancestorStateOfType(const TypeMatcher<BoostContainerState>());
    return container;
  }

  static BoostContainerState of(BuildContext context) {
    final BoostContainerState container =
        context.ancestorStateOfType(const TypeMatcher<BoostContainerState>());
    assert(container != null, 'not in flutter boost');
    return container;
  }

  String desc() => '{uniqueId=${settings.uniqueId},name=${settings.name}}';
}

class BoostContainerState extends NavigatorState {
Yacumima's avatar
dev  
Yacumima committed
120
  VoidCallback backPressedHandler;
Jidong Chen's avatar
init  
Jidong Chen committed
121 122 123 124 125

  String get uniqueId => widget.settings.uniqueId;

  String get name => widget.settings.name;

126 127
  Map get params => widget.settings.params;

Jidong Chen's avatar
init  
Jidong Chen committed
128 129 130 131 132 133 134 135 136 137 138
  BoostContainerSettings get settings => widget.settings;

  bool get onstage =>
      BoostContainerManager.of(context).onstageContainer == this;

  bool get maybeOnstageNext =>
      BoostContainerManager.of(context).subContainer == this;

  @override
  BoostContainer get widget => super.widget as BoostContainer;

139
  List<Route<dynamic>> routerHistory = <Route<dynamic>>[];
140

141 142
  bool multipleRouteMode = false;

Jidong Chen's avatar
init  
Jidong Chen committed
143 144 145 146 147 148 149 150 151 152 153
  ContainerNavigatorObserver findContainerNavigatorObserver(
      Navigator navigator) {
    for (NavigatorObserver observer in navigator.observers) {
      if (observer is ContainerNavigatorObserver) {
        return observer;
      }
    }

    return null;
  }

Yacumima's avatar
dev  
Yacumima committed
154 155 156
  @override
  void initState() {
    super.initState();
157
    backPressedHandler = () => maybePop();
Yacumima's avatar
dev  
Yacumima committed
158 159
  }

Jidong Chen's avatar
init  
Jidong Chen committed
160 161 162 163 164 165 166
  @override
  void didUpdateWidget(Navigator oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
167 168 169 170
    for (Route route in routerHistory) {
      GlobalRouteSettingsManager.instance.removeSettings(route);
    }

171
    routerHistory.clear();
172

173 174 175 176
    // 复用XPlatformPlugin后,每次dispose时都需要在这里反复通知Native更新Theme
//    SystemChrome.restoreSystemUIOverlays();
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle());

Jidong Chen's avatar
init  
Jidong Chen committed
177 178 179 180 181 182
    super.dispose();
  }

  void performBackPressed() {
    Logger.log('performBackPressed');

Yacumima's avatar
dev  
Yacumima committed
183
    backPressedHandler?.call();
Jidong Chen's avatar
init  
Jidong Chen committed
184 185
  }

186 187
  Route get topRoute => routerHistory.isNotEmpty ? routerHistory.last : null;

188 189
  @override
  Future<bool> maybePop<T extends Object>([T result]) async {
justin's avatar
justin committed
190
    if(routerHistory.isEmpty){
justin's avatar
justin committed
191
      pop(result);
justin's avatar
justin committed
192 193 194
      return true;
    }

justin's avatar
justin committed
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    final Route<T> route = routerHistory.last;
    final RoutePopDisposition disposition = await route.willPop();
    if (mounted) {
      switch (disposition) {
        case RoutePopDisposition.pop:
          pop(result);
          return true;
          break;
        case RoutePopDisposition.doNotPop:
          return false;
          break;
        case RoutePopDisposition.bubble:
          pop(result);
          return true;
          break;
      }
    }
justin's avatar
justin committed
213
    return false;
214 215
  }

Jidong Chen's avatar
init  
Jidong Chen committed
216 217
  @override
  bool pop<T extends Object>([T result]) {
218
    Route removedRoute;
justin's avatar
justin committed
219
    if (routerHistory.length >= 1) {
220
      removedRoute = routerHistory.removeLast();
221 222
    }

Jidong Chen's avatar
init  
Jidong Chen committed
223
    if (canPop()) {
224
         super.pop<T>(result);
225 226 227
         if (removedRoute != null) {
           GlobalRouteSettingsManager.instance.removeSettings(removedRoute);
         }
ColdPaleLight's avatar
ColdPaleLight committed
228 229 230 231 232
         if (Platform.isIOS && multipleRouteMode && !canPop()) {
           FlutterBoost.singleton.channel
               .invokeMethod<dynamic>('enablePopGesture', null);
           //开启native返回手势
         }
Jidong Chen's avatar
init  
Jidong Chen committed
233
    } else {
234 235
      if (T is Map<String, dynamic>) {
        FlutterBoost.singleton
236
            .closeInternal(uniqueId, result: result as Map<String, dynamic>);
237
      } else {
238
        FlutterBoost.singleton.closeInternal(uniqueId,);
Yacumima's avatar
Yacumima committed
239
      }
Jidong Chen's avatar
init  
Jidong Chen committed
240
    }
241
    return true;
Jidong Chen's avatar
init  
Jidong Chen committed
242 243
  }

244 245 246 247 248 249 250 251
  @override
  Future<T> push<T extends Object>(Route<T> route) {
    Route<T> newRoute;
    if (FlutterBoost.containerManager.prePushRoute != null) {
      newRoute = FlutterBoost.containerManager
          .prePushRoute(name, uniqueId, params, route);
    }

xgz's avatar
xgz committed
252
    if (multipleRouteMode && routerHistory.isNotEmpty) {
justin's avatar
justin committed
253 254 255
      ContainerNavigatorObserver.bindContainerManager().willPush(route, routerHistory.last);
    }

256 257
    Future<T> future = super.push<T>(newRoute ?? route);

258 259
    routerHistory.add(route);

260 261 262 263 264
    if (FlutterBoost.containerManager.postPushRoute != null) {
      FlutterBoost.containerManager
          .postPushRoute(name, uniqueId, params, newRoute ?? route, future);
    }

ColdPaleLight's avatar
ColdPaleLight committed
265 266 267 268 269
    if (Platform.isIOS && multipleRouteMode && canPop()) {
      FlutterBoost.singleton.channel
          .invokeMethod<dynamic>('disablePopGesture', null);
    }

270 271 272
    return future;
  }

Jidong Chen's avatar
init  
Jidong Chen committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  VoidCallback addLifeCycleObserver(BoostContainerLifeCycleObserver observer) {
    return FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
        (ContainerLifeCycle state, BoostContainerSettings settings) {
      if (settings.uniqueId == uniqueId) {
        observer(state, settings);
      }
    });
  }
}

class BoostContainerSettings {
  final String uniqueId;
  final String name;
  final Map params;
  final WidgetBuilder builder;

  const BoostContainerSettings(
      {this.uniqueId = 'default',
      this.name = 'default',
      this.params,
      this.builder});
}

class ContainerElement extends StatefulElement {
  ContainerElement(StatefulWidget widget) : super(widget);
}

class ContainerNavigatorObserver extends NavigatorObserver {
justin's avatar
justin committed
301
  static final Set<NavigatorObserver> boostObservers = Set<NavigatorObserver>();
Jidong Chen's avatar
init  
Jidong Chen committed
302 303 304 305

  ContainerNavigatorObserver();

  factory ContainerNavigatorObserver.bindContainerManager() =>
yangwu.jia's avatar
yangwu.jia committed
306
      ContainerNavigatorObserver();
Jidong Chen's avatar
init  
Jidong Chen committed
307

yangwu.jia's avatar
yangwu.jia committed
308 309
  VoidCallback addBoostNavigatorObserver(NavigatorObserver observer) {
    boostObservers.add(observer);
Jidong Chen's avatar
init  
Jidong Chen committed
310

yangwu.jia's avatar
yangwu.jia committed
311
    return () => boostObservers.remove(observer);
Jidong Chen's avatar
init  
Jidong Chen committed
312 313
  }

yangwu.jia's avatar
yangwu.jia committed
314 315
  void removeBoostNavigatorObserver(NavigatorObserver observer) {
    boostObservers.remove(observer);
Jidong Chen's avatar
init  
Jidong Chen committed
316 317
  }

justin's avatar
justin committed
318 319 320
  void willPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    for (NavigatorObserver observer in boostObservers) {
      if(observer is ContainerNavigatorObserver){
ColdPaleLight's avatar
ColdPaleLight committed
321
        if (observer == this) continue;
justin's avatar
justin committed
322 323 324 325 326
        ContainerNavigatorObserver  containerNavigatorObserver = observer as ContainerNavigatorObserver;
        containerNavigatorObserver.willPush(route, previousRoute);
      }
    }
  }
Jidong Chen's avatar
init  
Jidong Chen committed
327 328
  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
yangwu.jia's avatar
yangwu.jia committed
329
    for (NavigatorObserver observer in boostObservers) {
ColdPaleLight's avatar
ColdPaleLight committed
330
      if (observer == this) continue;
Jidong Chen's avatar
init  
Jidong Chen committed
331 332 333 334 335 336
      observer.didPush(route, previousRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
yangwu.jia's avatar
yangwu.jia committed
337
    for (NavigatorObserver observer in boostObservers) {
ColdPaleLight's avatar
ColdPaleLight committed
338
      if (observer == this) continue;
Jidong Chen's avatar
init  
Jidong Chen committed
339 340 341 342 343 344
      observer.didPop(route, previousRoute);
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
yangwu.jia's avatar
yangwu.jia committed
345
    for (NavigatorObserver observer in boostObservers) {
ColdPaleLight's avatar
ColdPaleLight committed
346
      if (observer == this) continue;
Jidong Chen's avatar
init  
Jidong Chen committed
347 348 349 350 351 352
      observer.didRemove(route, previousRoute);
    }
  }

  @override
  void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
yangwu.jia's avatar
yangwu.jia committed
353
    for (NavigatorObserver observer in boostObservers) {
ColdPaleLight's avatar
ColdPaleLight committed
354
      if (observer == this) continue;
Jidong Chen's avatar
init  
Jidong Chen committed
355 356 357 358
      observer.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    }
  }
}
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

class GlobalRouteSettingsManager {

  GlobalRouteSettingsManager._();

  static GlobalRouteSettingsManager instance = GlobalRouteSettingsManager._();

  final Map<Route,BoostRouteSettings> _routeSettingsMap = <Route,BoostRouteSettings>{};

  void addSettings(Route route,BoostRouteSettings settings) {
    _routeSettingsMap[route] = settings;
  }

  void removeSettings(Route route) {
    _routeSettingsMap.remove(route);
  }

  BoostRouteSettings getSettings(Route route) {
    return _routeSettingsMap[route];
  }

  bool contains(Route route) {
    return _routeSettingsMap[route] != null;
  }
}