Skip to content
Projets

À propos

Code push for Flutter, powered by dart_eval

Langages et environnements d’exécution

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
-1
in 15 days
-1
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

Star on Github License: BSD-3 Web example Github-sponsors

flutter_eval is a Flutter bridge library for dart_eval, and a solution enabling code-push, dynamic widgets, and runtime evaluation of Flutter code. It can be used to enable hot-swapping parts of your app with an over-the-air update, dynamically loading UI from a server, or evaluating code based on user input such as in a calculator. flutter_eval supports all platforms including iOS and is built on dart_eval's custom bytecode interpreter, making it very fast.

dart_eval pub package
flutter_eval pub package
eval_annotation pub package

For a live example, check out EvalPad.

Note: While flutter_eval supports most Flutter and Dart features, it does not support all of them. Existing code may need modification to work. You can see a list of supported widgets and classes here and a list of supported Dart features on the dart_eval Pub page.

See: Quickstart for code push | Quickstart for dynamic execution and server-driven UI | Supported widgets and classes

Quickstart for code push

First, run flutter pub add flutter_eval to install the package in your app.

At the root of your app, add a HotSwapLoader widget with a URI pointing to where you'll host the update file:

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return HotSwapLoader(
        uri: 'https://mysite.com/app_update/version_xxx.evc',
        child: MaterialApp(
          ...

Then, add HotSwap widgets throughout your app at every location you'd like to be able to dynamically update:

class MyHomePage extends StatelessWidget {
  
  @override
  Widget build(BuildContext context) {
    return HotSwap(
      id: '#myHomePage',
      args: [$BuildContext.wrap(context)],
      childBuilder: (context) => Scaffold(
        ...

Next, create a new Flutter package using flutter create --template=package. This can be nested inside your app's folder or located separately. Name it something appropriate, such as my_app_hot_update. We'll refer to this as the "hot update package" from now on.

Download flutter_eval.json matching the flutter_eval version and Flutter SDK used by your app from the Releases page (or generate it locally with flutter test --no-pub tool/export_bindings.dart).

In the root of the hot update package, create a folder called .dart_eval and a subfolder bindings. Place the downloaded flutter_eval.json file inside of this folder.

Your project structure should look like this:

├── .dart_eval
│   └── bindings
│       └── flutter_eval.json
├── pubspec.yaml
└── lib
    └── hot_update.dart

At the root of the hot update package, run flutter pub add eval_annotation.

Delete all the code from main.dart, including the main() function. For every HotSwap widget you'd like to update (you can update all, or just a few, or just one), create a top-level function with the @RuntimeOverride annotation referencing its ID:

@RuntimeOverride('#myHomePage')
Widget myHomePageUpdate(BuildContext context) {
  return Scaffold(
    ...
  )
}

Finally, install the matching dart_eval CLI:

dart pub global activate dart_eval

After installing, you can run:

dart_eval compile -o version_xxx.evc

If the steps were performed correctly, you should see the following in the console output:

Found binding file: .dart_eval\bindings\flutter_eval.json

as well as

Compiled $x characters Dart to $y bytes EVC in $z ms: version_xxx.evc

The resulting version_xxx.evc file will be in the root of the project and you can now upload it to the previously referenced server path.

If you run the app, you should see the contents of the HotSwap widgets replaced with the contents of their corresponding @RuntimeOverride functions.

HotSwap widgets can optionally specify a strategy to use when loading/applying updates, one of immediate, cache, or cacheApplyOnRestart. By default, HotSwapLoader uses immediate in debug/profile mode and cacheApplyOnRestart in release mode. You can also specify a placeholder widget to display when loading from the cache via the loading parameter.

For a complete example of code push, see examples/code_push_app and its subfolder hot_update.

Quickstart for dynamic execution and server-driven UI

To create a simple dynamic stateless widget, add and modify the following inside a build() method or as a child parameter:

return EvalWidget(packages: {
      'example': {
        'main.dart': '''
  import 'package:flutter/material.dart';
  
  class MyWidget extends StatelessWidget {
    MyWidget(this.name);
    final String name;

    @override
    Widget build(BuildContext context) {
      return Padding(
        padding: EdgeInsets.all(5.0),
        child: Column(children: [
            Container(
              color: Colors.red,
              child: Text('The name is ' + name)
            )
          ],
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
        )
      );
    }
  }''',
      },
    },
    assetPath: 'assets/program.evc',
    library: 'package:example/main.dart',
    function: 'MyWidget.',
    args: {'name': 'Example name'}
);

Internally, EvalWidget automatically switches between two modes:

  • When running in debug mode, it will dynamically compile the provided Dart code into EVC bytecode, save it to a file determined by assetPath, and run it in the dart_eval VM. This is slower, but allows you to make changes when developing with a hot restart.
  • When running in release mode, it will instead ignore the provided Dart code and attempt to load EVC bytecode, either from the assetPath or from a custom file, asset, or network URL specified by the optional uri parameter. This enables high performance at runtime, while still letting you dynamically swap out code by providing a new EVC file or URL.

If you are loading EVC bytecode from the network, you can specify an optional loading widget with the loading parameter.

flutter_eval includes two other helper Widgets for different use cases:

  • CompilerWidget will always compile and run provided Dart code, and never attempt to load EVC bytecode, regardless of whether the app is in debug or release mode. This is especially suitable for apps like calculators, 'learn to code' platforms, or user-scriptable automation tools. Though this mode is slower, the dart_eval compiler is very fast and will generally compile simple Flutter programs in ~0.1 second.
  • RuntimeWidget will always load EVC bytecode and does not provide a parameter to specify Dart code. This is recommended if you're compiling with the CLI - see below.

Calling functions and passing arguments

To instantiate a class with its default constructor, append a '.' to the class name.

Pass entrypoint arguments in a map keyed by their declared parameter names, including positional parameters. Omit optional parameters to use their defaults. An explicit null is passed as null. Primitives and collections need no wrappers.

E.g. for the following class:

class MyApp extends SomeWidget {
  MyApp(this.name, {Key? key, Color? color}) : super(key: key, color: color);

  final String name;
}

You could instantiate it in RuntimeWidget with:

return RuntimeWidget(
  uri: Uri.parse('asset:assets/program.evc'),
  library: 'package:example/main.dart',
  function: 'MyApp.',
  args: {'name': 'Jessica'}
);

You can also pass callbacks with $Function.

Security and permissions

flutter_eval inherits dart_eval's secure execution model which restricts access to the filesystem, network, and other sensitive APIs by default. flutter_eval extends this with security controls for MethodChannel and related APIs. To allow access to a MethodChannel, add a MethodChannelPermission to the permissions parameter of EvalWidget, CompilerWidget, or RuntimeWidget.

Supported widgets and classes

flutter_eval currently binds 171 classes, 74 enums, and 2 top-level functions (plus 239 opaque supporting types for signature compatibility) across Flutter's core libraries:

Library Support Key bound APIs
package:flutter/widgets.dart Partial (broad) Widget, StatelessWidget, StatefulWidget, State, BuildContext, Element, GlobalKey, WidgetsApp, Container, Column, Row, Center, Stack, Positioned, Align, Padding, Expanded, SizedBox, FittedBox, FractionallySizedBox, AspectRatio, Baseline, ColoredBox, ClipRRect, LayoutBuilder, Builder, Spacer, Text, DefaultTextStyle, Icon, IconData, Image, GestureDetector, ListView, Scrollable, ScrollController, Navigator, NavigatorState, Route, PageRoute, OverlayEntry, MediaQuery, Directionality, FocusNode, FocusScopeNode, TextEditingController, WidgetStateProperty, runApp
package:flutter/material.dart Partial MaterialApp, Scaffold, ScaffoldMessenger, AppBar, Drawer, SnackBar, Card, ListTile, SwitchListTile, FloatingActionButton, ElevatedButton, TextButton, IconButton, ButtonStyle, ButtonStyleButton, InkWell, TextField, Theme, ThemeData, TextTheme, MaterialPageRoute, Colors, MaterialColor, MaterialAccentColor, Icons, VisualDensity
package:flutter/painting.dart Partial (broad) Alignment, AlignmentGeometry, EdgeInsets, EdgeInsetsGeometry, BorderRadius, BorderRadiusGeometry, Border, BoxBorder, BorderSide, ShapeBorder, BoxDecoration, Decoration, ColorSwatch, TextStyle, TextPainter, TextSpan, InlineSpan, ImageProvider, NetworkImage, MemoryImage, ResizeImage, Axis, AxisDirection, BoxFit, BoxShape, TextOverflow, axisDirectionToAxis
package:flutter/foundation.dart Partial Key, LocalKey, ValueKey, UniqueKey, Listenable, ValueListenable, ChangeNotifier, ValueNotifier, Diagnosticable, DiagnosticsNode, DiagnosticsProperty, DiagnosticPropertiesBuilder, DiagnosticsSerializationDelegate, TextTreeConfiguration
package:flutter/animation.dart Partial Animation, AnimationController, AnimationStatus, Curve, ParametricCurve, Curves, Cubic, Interval, SawTooth, Threshold, ElasticInCurve, ElasticOutCurve, ElasticInOutCurve
package:flutter/gestures.dart Partial TapDownDetails, TapUpDetails, DragDownDetails, DragStartDetails, DragUpdateDetails, DragEndDetails, LongPressDownDetails, LongPressStartDetails, LongPressMoveUpdateDetails, LongPressEndDetails, Velocity
package:flutter/services.dart Partial MethodChannel, MethodCall, MethodCodec, BinaryMessenger, KeyEvent, KeyDownEvent, KeyUpEvent, KeyRepeatEvent, KeyboardKey, LogicalKeyboardKey, PhysicalKeyboardKey
package:flutter/rendering.dart Partial Constraints, BoxConstraints, MainAxisAlignment, CrossAxisAlignment, MainAxisSize, FlexFit, StackFit, HitTestBehavior
package:flutter/scheduler.dart Partial Ticker, TickerFuture, TickerProvider
package:flutter/cupertino.dart Minimal CupertinoDynamicColor
dart:ui Partial Color, Offset, Size, Rect, Radius, Canvas, Paint, Path, Picture, PictureRecorder, Image, FontWeight, TextDecoration, Locale, SemanticsAction, plus 25 enums (Clip, TextAlign, TextDirection, BlendMode, PointerDeviceKind, etc.)

See .dart_eval/bindgen.yaml for the complete list of bound types and members. Some classes have partial member coverage, and supporting SDK types marked opaque: true can be passed through typed APIs without exposing their own constructors or members.

App size measurements

Measured on Flutter 3.47.0 with flutter_eval v1.0.1 (flutter build apk --release --no-tree-shake-icons):

App Baseline (arm64-v8a) with EvalWidget / RuntimeWidget with CompilerWidget
Material 3 Demo 18.3 MB 28.3 MB (+10.0 MB) 32.7 MB (+14.4 MB)
Flutter Counter 14.8 MB 25.8 MB (+11.0 MB) 30.2 MB (+15.4 MB)

These sizes are for single-ABI arm64-v8a split APKs, which reflect typical Play Store / App Store downloads (combined 3-ABI APKs are ~3x larger: 53.0 MB → 83.0 MB / 96.2 MB for Material 3 Demo). They do not include an EVC bytecode file, which is typically 20–100 KB (or 6–30 KB gzipped) and can be downloaded at runtime rather than bundled with the app.

Notes:

  • EvalWidget and RuntimeWidget tree-shake the dart_eval compiler out of release builds; CompilerWidget includes the compiler and package:analyzer for on-device compilation.
  • Release builds using flutter_eval currently require --no-tree-shake-icons due to dynamic IconData construction, which accounts for ~1.6 MB of the APK size increase (the full MaterialIcons-Regular.otf font).

Advanced usage

Using flutter_eval requires two main steps: compiling the Dart code to EVC bytecode, and executing the resultant EVC bytecode. Since you cannot currently expect all existing Flutter/Dart code to work with flutter_eval, it's recommended to run both steps in your app during development:

class ExampleState extends State<Example> {
  late Runtime runtime;

  @override
  void initState() {
    super.initState();

    final compiler = Compiler();
    compiler.addPlugin(flutterEvalPlugin);

    final program = compiler.compile({
      'example': { 'main.dart': '''
          import 'package:flutter/material.dart';
          
          class HomePage extends StatelessWidget {
            HomePage(this.number);
            final int number;
            
            @override
            Widget build(BuildContext context) {
              return Padding(
                padding: EdgeInsets.all(2.3 * 5),
                child: Container(
                  color: Colors.green,
                  child: Text('Current amount: ' + number.toString())
                )
              );
            }
          }
        ''' }
    });

    final file = File('out.evc');
    file.writeAsBytesSync(program.write());
    print('Wrote out.evc to: ' + file.absolute.uri);
    
    runtime = Runtime.ofProgram(program);
    runtime.addPlugin(flutterEvalPlugin);
  }

  @override
  Widget build(BuildContext context) {
    return runtime!.executeLib('package:example/main.dart', 'HomePage.',
        arguments: {'number': 55}) as Widget;
  }
}

With this setup you can quickly see any errors in the code. However, we're also continuously writing the EVC bytecode to a file out.evc. This file contains the compiled bytecode created from the Dart source and when releasing an app to production, it's all you need. Running the compiler in your production app at runtime, while possible, is strongly discouraged as it is much slower than simply using the generated output. EVC bytecode is platform-agnostic, so you can generate the out.evc file using Flutter Desktop and use it in a Flutter Mobile app with no issues.

After it's generated, you can use it in an app like so:

import 'dart:typed_data';
import 'package:flutter/services.dart' show rootBundle;

class ExampleState extends State<Example> {
  Runtime? runtime;

  @override
  void initState() {
    super.initState();
    
    rootBundle.load('assets/out.evc').then((bytecode) => setState(() {
      runtime = Runtime(Uint8List.fromList(Uint8List.sublistView(bytecode)).buffer);
      runtime!.addPlugin(flutterEvalPlugin);
    }));
  }

  @override
  Widget build(BuildContext context) {
    if (runtime == null) return CircularProgressIndicator();
    return runtime!.executeLib('package:example/main.dart', 'HomePage.',
        arguments: {'number': 55}) as Widget;
  }
}

You can also load out.evc over the network. In a large app, you may want to consider gzip compression as EVC bytecode compresses very well (around a 4x ratio).

Explorer des projets similaires

Chargement…