Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Preface: Today just see, can [carry own original article] participate in “programmer essential small knowledge” activity, very excited. Remember before there are a few technical articles on a platform, I feel the nuggets technology atmosphere is stronger, I want to move over.

The Go end of go-flutter sends messages to the Dart end of Go-flutter.

The body of the

For the Go-FLUTTER plug-in, there are many situations where messages need to be sent from the GO terminal to the Dart terminal, such as timed and asynchronous processes.

If only Dart actions are used to call the functions of the Go-flutter plugin, the web page will send the request and the server will return the response to the page.

If code on the GO side of the Flutter could send messages to the Dart side, it would be somewhat like a WebSocket, enabling bidirectional message delivery.

The GO end of the Go-flutter sends messages to the Dart end, which is not known how to call at first. Also with the idea of a zhihu friend, once thought whether to use TCP to achieve. But the personal TCP also do not understand, then give up.

Just a few days ago, I realized that the need for Go-flutter is widespread and should be implemented. Therefore, I searched the Github repository of Go-flutter and found the specific usage of go-flutter in the Wiki of the plugin for Go-flutter.

Go sends messages to the message channel, and Dart listens for messages and processes them.

Related code (CV is the version of the Go side sending messages to the Dart side)

Go side code (above link content CV to here) :

// Golang
channel := plugin.NewMethodChannel(messenger, "samples/demo", plugin.StandardMethodCodec{})
err := p.channel.InvokeMethod("test", nil)
// error handling..
Copy the code

Dart side code (CV from the link above) :

// Dart
const platform_channel = MethodChannel("samples/demo");
platform_channel.setMethodCallHandler((MethodCall methodCall) async {
  print(methodCall.method); // prints: test
});
Copy the code

There is also a method for the Go endpoint to send messages to the Dart endpoint and wait for the Dart endpoint to respond.

Go side code (above link content CV to here) :

// Golang
channel := plugin.NewMethodChannel(messenger, "samples/demo", plugin.StandardMethodCodec{})
reply, err := channel.InvokeMethodWithReply("test", nil) // blocks the goroutine until reply is avaiable
// error handling..
spew.Dump(reply) // prints 5 seconds later: (string) (len=21) "reply from dart: test"
Copy the code

Dart side code (CV from the link above) :

// Dart
const platform_channel = MethodChannel("samples/demo");
platform_channel.setMethodCallHandler((MethodCall methodCall) async {
  print(methodCall.method); // prints: test
  await Future.delayed(Duration(seconds: 5));
  return "reply from dart: " + methodCall.method;
});
Copy the code

The Go end sends a message and waits for the Dart end to respond. I just tried the use of the Go side sending messages to the Dart side, which was added to the project in section 1.

GitHub – bettersun/hellogoflutter

It adds a timer to send messages from the Go side to the Dart side.

Main code:

The Go end:

Define function:

Func sendInterval(channel * plugin.methodChannel) {ticker := time.newticker (time.second * 1) go func()  { for _ = range ticker.C { fmt.Println("sendInterval") err := channel.InvokeMethod("interval", time.Now().Format("2006/01/02 15:04:05")) if err ! = nil { log.Println(err) } } }() }Copy the code

The function defined above is run in the new Goroutine when the plug-in is initialized.

Func (HelloPlugin) InitPlugin(messenger plugin.BinaryMessenger) error {channel := plugin.NewMethodChannel(messenger, channelName, plugin.StandardMethodCodec{}) channel.HandleFunc(hello, HelloFunc) channel.handleFunc (message, messageFunc) // Send a message to Dart go sendInterval(channel) return nil}Copy the code

The Dart end:

Add a listener to the message channel at initState ().

Method is the name of the function sent by the Go end.

The arguments are the return value of the function sent from the Go side. The type is Dynamic and needs to be resolved depending on the type.

class _HelloPageState extends State<HelloPage> { String timeNow = ''; @ override void initState () {/ / listen Go end. Sending a message HelloPlugin channel. SetMethodCallHandler ((MethodCall MethodCall) async {the if (methodCall.method == 'interval') { setState(() { print(methodCall.arguments); timeNow = methodCall.arguments; }); }}); super.initState(); } / /... }Copy the code

The running result is as follows. The time displayed in the title bar is the time sent from the Go terminal.