返回

结构体参数从Go传递至Flutter

前端

在Go-Flutter开发中,插件可以传递参数,但仅限于简单类型。如果需要传递结构体之类的复杂类型,就需要借助MethodChannel来传递消息。本文将详细介绍如何从Go将结构体参数传递至Flutter。

准备工作

在开始之前,请确保您已经满足以下条件:

  • 您已经安装了Go和Flutter。
  • 您已经创建了一个Flutter项目。
  • 您已经创建了一个Go插件项目。

创建Go结构体

首先,您需要在Go项目中创建一个结构体来表示要传递的数据。例如,您可以创建一个名为Person的结构体,如下所示:

type Person struct {
    Name string
    Age  int
}

将结构体转换为Map

接下来,您需要将结构体转换为Map,以便能够通过MethodChannel传递。您可以使用encoding/json包来实现这一点。例如,您可以使用以下代码将Person结构体转换为Map:

package main

import (
    "encoding/json"

    "github.com/go-flutter-desktop/go-flutter"
)

// Person represents a person.
type Person struct {
    Name string
    Age  int
}

func main() {
    // Create a Person struct.
    person := Person{
        Name: "John Doe",
        Age:  30,
    }

    // Convert the Person struct to a map.
    data, err := json.Marshal(person)
    if err != nil {
        panic(err)
    }

    // Create a MethodChannel.
    channel := go_flutter.NewMethodChannel("com.example.myapp/person")

    // Send the map to the Flutter side.
    channel.InvokeMethod("setPerson", data)
}

接收Map并在Flutter中解析

在Flutter项目中,您需要创建一个MethodChannel来接收Map。您可以使用以下代码创建一个MethodChannel:

import 'package:flutter/services.dart';

// Create a MethodChannel.
const methodChannel = MethodChannel('com.example.myapp/person');

// Receive the map from the Go side.
methodChannel.setMethodCallHandler((MethodCall call) async {
    // Parse the map.
    final data = json.decode(call.arguments);

    // Create a Person object.
    final person = Person.fromJson(data);

    // Do something with the Person object.
});

定义Person类

在Flutter项目中,您还需要定义一个Person类来表示从Go侧接收到的数据。您可以使用以下代码定义Person类:

class Person {
  final String name;
  final int age;

  Person({this.name, this.age});

  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(
      name: json['name'],
      age: json['age'],
    );
  }
}

现在,您可以使用Person对象来在Flutter中处理从Go侧接收到的数据。