Executing Dynamic Scripts
This article is for informational purposes only.
Using this approach can significantly affect the performance and security of your applications. Use it at your own risk.
Duit implements a fairly powerful system for state management and server interaction, but in some cases, frequent server requests can be excessive.
Consider the following scenario: on an authentication form in an application, there is a field where the user must enter their phone number. We'll refer to this field simply as phone. A common requirement when implementing such widgets is input validation during entry. In our case, we need to check if the phone field matches the correct pattern.
How this can be implemented using Duit:
- On the server side, associate the
TextFieldwidget responsible for phone entry with an action that sends the current widget value to the backend. - Validate the received value and send the validation result as a new widget state.
- Update the state.
In such an implementation, serious problems are visible to the naked eye, such as frequent server requests for validation due to invoking an action for every newly entered character. And, of course, such use creates side-effects when updating attributes and reduces application performance.
Since Duit does not implement computed expression handling, an alternative path is suggested for implementing such functionality — using a third-party execution environment to interpret code, execute a script, and return the execution result to the Dart side.
A full implementation example of this approach can be found in the duit_hetu_extension repository.
When using scripts, we would need to associate the TextField widget responsible for phone entry on the server side with a script-action that will validate input parameters and return the necessary widget state depending on the validation result. And also implement the necessary abstractions for script processing on the client side.
Let's consider all the necessary steps for implementation in detail.
Choosing a Language and Execution Environment
Dart is a compiled programming language. For us, this means that we cannot execute Dart code in our program that was received at runtime, for example, as a string or a file.
In this regard, one of the main requirements when choosing a language for implementing scripts is the ability to interpret the received code "on the fly" and then execute it. Virtual machines of other programming languages (including Dart) are suitable for these purposes.
Example of available execution environments:
- dart_eval — a compiler and bytecode interpreter for the Dart language, written in Dart, providing dynamic execution and code delivery for Flutter and Dart AOT.
- lua_dardo — a Lua virtual machine written in Dart, implementing Lua version 5.3.
- hetu_script — a lightweight scripting language written exclusively in Dart for embedding in Flutter applications.
All following examples will be considered in the context of hetu_script integration as the most efficient solution.
Implementing ScriptingCapabilityDelegate
In the new version of Duit, script management is handled through a capabilities system. A delegate implementing the ScriptingCapabilityDelegate mixin is responsible for processing and executing dynamic scripts.
final class HetuInitOptions {
Map<String, Function> externalFunctions;
ExternalHetuConfig config;
HetuInitOptions({
required this.config,
this.externalFunctions = const {},
});
}
In this specific example, we've created a HetuInitOptions class that will be used to configure the execution environment.
The next step is to implement the delegate itself.
final class HetuScriptingManager with ScriptingCapabilityDelegate {
late final UIDriver _driver;
late final Hetu _hetuInstance;
final HetuInitOptions options;
HetuScriptingManager({
required this.options,
});
void linkDriver(UIDriver driver) {
_driver = driver;
}
Future<void> initScriptingCapability() async {
_hetuInstance = Hetu(
config: options.config.toHetuConfig(),
)..init(
externalFunctions: {
...options.externalFunctions,
"request": (
String url,
Map<String, dynamic> meta,
Map<String, dynamic> body,
) async {
// Use the driver transport to perform requests
return await _driver.request(
url,
meta,
body,
);
}
},
);
}
Future<Map<String, dynamic>?> execScript(
String functionName, {
String? url,
Map<String, dynamic>? meta,
Map<String, dynamic>? body,
}) async {
return await _hetuInstance.invoke(
functionName,
positionalArgs: [
url,
meta,
body,
],
);
}
Future<void> evalScript(String source) async {
await _hetuInstance.eval(source);
}
void releaseResources() {
// Resource cleanup if necessary
}
}
The ScriptingCapabilityDelegate mixin requires overriding several methods. Let's examine their purpose in detail.
linkDriver
The linkDriver method is called automatically during driver initialization and passes a reference to the UIDriver instance. This allows the delegate to interact with other parts of the system, for example, using transport for network requests.
initScriptingCapability
The initScriptingCapability method is responsible for initializing the execution environment. This is where you should configure the virtual machine, register external functions, etc.
evalScript
The evalScript method performs script compilation and interpretation during the parsing stage of the Duit JSON structure. If a widget has an associated action and that action is a ScriptAction, its source code will be processed by this method.
execScript
The execScript method is called during action execution. The required functionName parameter is the name of the function to call. The url, meta, and body parameters during the action call will be passed as arguments to the script automatically. Where url is the request address or event name, meta is metadata, and body is the request body or useful data for performing the action.
The final step is to pass the created manager to the driver constructor. It is recommended to use DuitDriverCompat for working with the capability-based API.
//main.dart
late final DuitDriverCompat driver;
void initState() {
driver = DuitDriverCompat(
transportManager: HttpTransportManager(
url: "/layout",
baseUrl: "http://localhost:3000",
),
scriptingManager: HetuScriptingManager(
options: HetuInitOptions(
config: ExternalHetuConfig(),
),
),
);
super.initState();
}
Creating a ScriptAction
Let's look at how to create a script action. DSL libraries provide special functions for convenient creation of such actions.
- TypeScript
- Go
const action = ScriptAction(
"script1", //event name
{
"sourceCode": "fun testFn() {...}", //script text
"functionName": "testFn", //function name to call
},
[
{
id: "dependency1",
target: "value"
},
],
);
action := NewScriptAction(
"script1",
[]*ActionDependency{
{
Id: "dependency1",
Target: "value",
},
},
&ScriptData{
SourceCode: `fun testFn() {...}`, //script text
FunctionName: "function name", //function name to call
},
)