Why Use magic_webgen?

The magic_webgen Flutter package bridges native C libraries and Flutter by compiling C source files to WebAssembly (Wasm) and auto‑generating Dart bindings. This is ideal when you need raw computational speed, deterministic memory usage, or want to reuse battle‑tested C algorithms without rewriting them in Dart.

  • High‑performance image processing
  • Cryptographic operations
  • Physics simulations
  • Audio DSP pipelines
  • Porting legacy C libraries to Flutter
Tip: magic_webgen works best for web targets. For mobile you will still need a native FFI approach.

Installation

Add the package to your Flutter project with the standard CLI command:

Code
flutter pub add magic_webgen

After the command completes, run flutter pub get to fetch the dependencies.

Project Setup

magic_webgen expects a small configuration file (commonly magic_webgen.yaml) that tells the tool which C sources to compile and how the Dart API should look. A minimal example looks like this:

Code
# magic_webgen.yaml
c_sources:
  - lib/src/fib.c
output_dir: lib/generated
module_name: fib

Place your C files under lib/src (or any folder you prefer) and make sure a C toolchain (e.g., clang or gcc) is available in your PATH. The tool will invoke emcc under the hood, so having Emscripten installed is also required for Wasm generation.

Step‑by‑Step Example: Fibonacci in C → Dart

1. Write the C function

Code
// lib/src/fib.c
int fib(int n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}

2. Configure magic_webgen

Create magic_webgen.yaml as shown earlier, pointing to fib.c and setting module_name: fib. This tells the generator to produce a Dart file named fib.dart inside lib/generated.

3. Run the code generator

Execute the following command from your project root:

Code
flutter pub run magic_webgen:generate

The command compiles fib.c to fib.wasm and writes lib/generated/fib.dart with a type‑safe binding class.

4. Use the generated binding in Flutter

Import the generated file and initialise the Wasm module before calling any function:

Code
import 'package:my_app/generated/fib.dart';

void main() async {
  // Ensure the Wasm module is loaded before calling any function.
  await FibBindings.initialize();
  int result = FibBindings.fib(10);
  print('Fibonacci(10) = $result'); // Expected output: 55
}

The FibBindings class is created by magic_webgen and abstracts away the low‑level Wasm loading, memory allocation, and type conversion.

5. Add the Wasm asset to pubspec.yaml

Code
flutter:
  assets:
    - lib/generated/fib.wasm

Including the Wasm file as an asset ensures it is bundled with your web build.

Mistakes to Avoid

  • Skipping the asset declaration: The Wasm binary must be listed under flutter.assets, otherwise the runtime will throw a load error.
  • Using mobile platforms only: magic_webgen currently targets web (Wasm). For iOS/Android you need a different FFI strategy.
  • Neglecting bundle size: Each Wasm module adds to the download payload. Keep modules small and consider lazy‑loading if appropriate.
  • Assuming source‑level debugging works: Debugging Wasm is more limited than native C. Use console logs in the generated Dart wrapper or test the C code separately.

Best Practices

Tip: Integrate magic_webgen into your CI pipeline. The flutter pub run magic_webgen:generate command can be run as a pre‑build step to guarantee that generated bindings are always up‑to‑date.
  • Keep C source files self‑contained and avoid platform‑specific APIs that cannot be compiled to Wasm.
  • Expose only the functions you need; each exported function adds to the Wasm export table.
  • Validate input ranges in Dart before passing values to Wasm to prevent undefined behaviour.

Where to Find More Information

The official documentation, including advanced configuration options, is available on Pub.dev:

If any detail is unclear, verify the latest usage guidelines on the package’s Pub.dev page or its GitHub repository.

Frequently Asked Questions

Does magic_webgen work on mobile platforms?

No. magic_webgen generates WebAssembly modules, which are supported on Flutter web. For iOS and Android you need a native FFI solution such as dart:ffi or flutter_rust_bridge.

What C toolchain is required?

You need a C compiler (e.g., clang or gcc) and Emscripten (emcc) in your PATH because magic_webgen uses emcc to produce the Wasm binary.

How do I keep the bundle size small?

Only export the functions you need, split large libraries into multiple Wasm modules, and consider lazy‑loading modules when they are first required.

Can I use magic_webgen in a CI/CD pipeline?

Yes. Add <code>flutter pub run magic_webgen:generate</code> as a pre‑build step. Ensure the CI environment has the required C toolchain and Emscripten installed.

Where are the generated Dart files located?

By default they are placed in the directory specified by <code>output_dir</code> in <code>magic_webgen.yaml</code>, typically <code>lib/generated</code>.