Home > Enterprise >  How to use dart:js and dart:html for a web and mobile code base? Conditional import?
How to use dart:js and dart:html for a web and mobile code base? Conditional import?

Time:07-06

I want to support running my app on mobile and on web, for the web version, I need to call a javascript library, therefore I call a method channel as follows

My app.js file:

function redirectToStripe(sessionId) {

    // ...
}

In my index.html I have added this

<script src="app.js" defer></script>

then I call my js function from dart like this:

import 'dart:js' as js;

redirectToStripe(sessionId) {
  js.context.callMethod('redirectToStripe', sessionId);
}

This all works as expect, however the problem is, when I try to run my app on mobile (iOS or Android) it doesn't compile because the dart:js package is not found.

Is there a work around, something like I only import dart:js when I'm on web or something similar?

CodePudding user response:

Using Flutter, the package stripe_ckeckout can be combined with flutter_stripe.

This allows one to call this when using Flutter Web without having to resort to Javascript:

// this is Flutter / Dart code, forwarding the Browser to Stripe
final result = await redirectToCheckout(
  context: context,
  sessionId: sessionId,
  publishableKey: Stripe.publishableKey,
  successUrl: stripeHelper.getSuccessUrl(),
  canceledUrl: stripeHelper.getCancelUrl(),
);

When building Flutter for Web AND Mobile, a conditional import may look like like below. This allows one to use the same code base for Mobile (Stripe PaymentSheet) and Web (Stripe Checkout).

This is primarily for getting dynamic return URLs for Stripe Checkout and avoid build errors when building for mobile.

import 'srv_stripe_env_stub.dart'  
  if (dart.library.io) 'srv_stripe_env_io.dart'
  if (dart.library.html) 'srv_stripe_env_html.dart';
abstract class StripeHelperAbs {
  ...
}

// srv_stripe_env_stub.dart (yes, same class name)
class StripeHelperImpl extends StripeHelperAbs {
 ...
}

// srv_stripe_env_io.dart (yes, same class name)
class StripeHelperImpl extends StripeHelperAbs { 
  ...
}

// srv_stripe_env_html.dart (yes, same class name)
class StripeHelperImpl extends StripeHelperAbs {
  ...
}

  • Related