Uma ponte JavaScript moderna e multiplataforma, por meio da qual você pode invocar funções um do outro de forma síncrona ou assíncrona entre JavaScript e Dart.
Orientação gerada a partir de informações públicas. Apenas para referência.
dsbridge_flutter é um bridge JavaScript multiplataforma que permite chamadas síncronas ou assíncronas entre JavaScript e Dart em aplicativos Flutter. Ele suporta Android, iOS e macOS, permitindo que desenvolvedores integrem conteúdo da web com funcionalidades nativas. O bridge facilita a comunicação bidirecional, tornando-o ideal para o desenvolvimento de aplicativos híbridos onde visualizações da web interagem com código nativo. Seu design leve e API simples simplificam a integração em projetos existentes.
Casos de uso
Integrando visualizações da web com recursos nativos do Flutter
Habilitar a comunicação em tempo real entre web e Dart
Construindo aplicativos móveis híbridos com componentes da web
Implementando callbacks personalizados de JavaScript para Dart
Suporte a atualizações dinâmicas da interface via JavaScript
Conectando lógica baseada na web com a lógica de negócios do Flutter
Principais recursos
invocação bidirecional de função
Chamadas síncronas e assíncronas
Suporte multiplataforma (Android, iOS, macOS)
API leve e fácil de integrar
Canal de comunicação seguro
Suporta tipos de dados complexos
Indicado para
desenvolvedores de aplicativos híbridos
Integradores de visualização da web
Desenvolvedores Flutter usando JavaScript
Aplicativos que exigem integração estreita com o nativo da web
Equipes construindo interfaces dinâmicas e interativas
Projetos que precisam de troca de dados em tempo real
Considerações
Requer um manuseio cuidadoso da segurança ao expor funções Dart para JavaScript
Pode ser necessário validação adicional para entradas de JavaScript não confiáveis
Não adequado para operações de alta frequência e baixa latência
Documentação limitada em comparação com pacotes maduros
Sobrecarga de desempenho potencial com grandes transferências de dados
É necessário gerenciar o ciclo de vida dos pontes para evitar vazamentos de memória
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
DSBridge for Flutter
Modern cross-platform JavaScript bridge, through which you can invoke each other's functions synchronously or asynchronously between JavaScript and Flutter applications.
Dart APIs must be registered with registerFunction in register function.
Note that if you use the --obfuscate option to obfuscate Dart code when building your application, you need to annotate the function with @pragma('vm:entry-point') or use the second parameter functionName of registerFunction to specify the function name.
Namespaces can help you better manage your APIs, which is very useful in hybrid applications, because these applications have a large number of APIs. DSBridge allows you to classify API with namespace. The namespace can be multilevel, between different levels with '.' division.
Debug mode
In debug mode, some errors will be prompted by a popup dialog , and the exception caused by the dart APIs will not be captured to expose problems.
Progress Callback
Normally, when a API is called to end, it returns a result, which corresponds one by one. But sometimes a call need to repeatedly return multiple times, Suppose that on the Flutter side, there is a API to download the file, in the process of downloading, it will send the progress information to JavaScript many times, then JavaScript will display the progress information on the H5 page. Oh...You will find it is difficult to achieve this function. Fortunately, DSBridge supports Progress Callback. You can be very simple and convenient to implement a call that needs to be returned many times. Here's an example of a countdown:
In Dart
voidcallProgress(dynamic args, CompletionHandler handler) {
var i = 10;
final timer = Timer.periodic(constDuration(seconds: 1), (timer) {
if (i == 0) {
timer.cancel();
handler.complete(0);
} else {
handler.setProgressData(i--);
}
});
}
In JavaScript
dsBridge.call("callProgress", function (value) {
document.getElementById("progress").innerText = value
})
For the complete sample code, please refer to the example project.
JavaScript popup box
For JavaScript popup box functions (alert/confirm/prompt), DSBridge has implemented them all by default, if you want to custom them, set the corresponding callback in DWebViewController. The default dialog box implemented by DSBridge is modal. This will block the UI thread.
API Reference
Dart API
In Dart, the object that implements the JavaScript interfaces is called Dart API object.
Call the JavaScript API. If a handler is given, the JavaScript handler can respond. the handlerName can contain the namespace. The handler will be called in Dart main isolate.
Example:
_controller.callHandler('append', args: ["I", "love", "you"],
handler: (retValue) {
print(retValue.toString());
});
/// call with namespace 'syn', More details to see the Demo project
_controller.callHandler('syn.getInfo', handler: (retValue) {
print(retValue.toString());
});
DWebViewController.javaScriptCloseWindowListener
DWebViewController calls callback when JavaScript calls window.closeyou can provide a callback to add your handler.
Test whether the handler exist in Dart, the handlerName can contain the namespace.
type: optional["all"|"syn"|"asyn" ], default is "all".
dsBridge.hasNativeMethod('testAsyn')
//test namespace method
dsBridge.hasNativeMethod('test.testAsyn')
// test if exist a asynchronous function that named "testSyn"
dsBridge.hasNativeMethod('testSyn','asyn') //false
Finally
If you like DSBridge for Flutter, please click star/like to let more people know it, Thanks!