ethanblake4/flutter_eval
概要
Code push for Flutter, powered by dart_eval
言語・ランタイム計測したスター増加
- 24時間
- 0
- 7日間
- -1
- 15日間
- -1
- 1か月
- 履歴を収集中
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナル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 | |
|---|---|
| flutter_eval | |
| eval_annotation |
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
uriparameter. 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:
CompilerWidgetwill 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.RuntimeWidgetwill 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:
EvalWidgetandRuntimeWidgettree-shake thedart_evalcompiler out of release builds;CompilerWidgetincludes the compiler andpackage:analyzerfor on-device compilation.- Release builds using
flutter_evalcurrently require--no-tree-shake-iconsdue to dynamicIconDataconstruction, which accounts for ~1.6 MB of the APK size increase (the fullMaterialIcons-Regular.otffont).
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).
関連プロジェクトを探す
読み込み中…