initState method

  1. @override
void initState()
override

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then be sure to subscribe and unsubscribe properly in initState, didUpdateWidget, and dispose:

  • In initState, subscribe to the object.
  • In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
  • In dispose, unsubscribe from the object.

You should not use BuildContext.dependOnInheritedWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.dependOnInheritedWidgetOfExactType can be used there.

Implementations of this method should start with a call to the inherited method, as in super.initState().

Implementation

@override
void initState() {
  super.initState();
  services = PaypalServices(
    sandboxMode: widget.sandboxMode,
    clientId: widget.clientId,
    secretKey: widget.secretKey,
  );
  setState(() {
    navUrl = widget.sandboxMode
        ? 'https://api.sandbox.paypal.com'
        : 'https://www.api.paypal.com';
  });
  // Enable hybrid composition.
  loadPayment();

  // #docregion platform_features
  late final PlatformWebViewControllerCreationParams params;
  if (WebViewPlatform.instance is WebKitWebViewPlatform) {
    params = WebKitWebViewControllerCreationParams(
      allowsInlineMediaPlayback: true,
      mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
    );
  } else {
    params = const PlatformWebViewControllerCreationParams();
  }

  final WebViewController controller =
      WebViewController.fromPlatformCreationParams(params);
  // #enddocregion platform_features

  controller
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000))
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          debugPrint('WebView is loading (progress : $progress%)');
        },
        onPageStarted: (String url) {
          setState(() {
            pageLoading = true;
            loadingError = false;
          });
          debugPrint('Page started loading: $url');
        },
        onPageFinished: (String url) {
          setState(() {
            navUrl = url;
            pageLoading = false;
          });
        },
        onWebResourceError: (WebResourceError error) {
          debugPrint('''
            Page resource error:
            code: ${error.errorCode}
            description: ${error.description}
            errorType: ${error.errorType}
            isForMainFrame: ${error.isForMainFrame}
        ''');
        },
        onNavigationRequest: (NavigationRequest request) async {
          if (request.url.startsWith('https://www.youtube.com/')) {
            debugPrint('blocking navigation to ${request.url}');
            return NavigationDecision.prevent;
          }
          if (request.url.contains(widget.returnURL)) {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (context) => CompletePayment(
                      url: request.url,
                      services: services,
                      executeUrl: executeUrl,
                      accessToken: accessToken,
                      onSuccess: widget.onSuccess,
                      onCancel: widget.onCancel,
                      onError: widget.onError)),
            );
          }
          if (request.url.contains(widget.cancelURL)) {
            final uri = Uri.parse(request.url);
            await widget.onCancel(uri.queryParameters);
            // ignore: use_build_context_synchronously
            Navigator.of(context).pop();
          }
          debugPrint('allowing navigation to ${request.url}');
          return NavigationDecision.navigate;
        },
        onUrlChange: (UrlChange change) {
          debugPrint('url change to ${change.url}');
        },
      ),
    )
    ..addJavaScriptChannel(
      'Toaster',
      onMessageReceived: (JavaScriptMessage message) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(message.message)),
        );
      },
    );

  // #docregion platform_features
  if (controller.platform is AndroidWebViewController) {
    AndroidWebViewController.enableDebugging(true);
    (controller.platform as AndroidWebViewController)
        .setMediaPlaybackRequiresUserGesture(false);
  }
  // #enddocregion platform_features

  _controller = controller;
}