Flutter BOS网关查看插件bos_gateway_viewer的使用

Flutter BOS网关查看插件bos_gateway_viewer的使用

需求

安装

pubspec.yaml 文件中添加 bos_gateway_viewer 依赖。

dependencies:
  bos_gateway_viewer: ^x.y.z

Web 平台支持

web/index.html 文件的 <head> 部分添加以下脚本:

<head>
    <!-- ... -->
    <script type="application/javascript" src="/assets/packages/flutter_inappwebview_web/assets/web/web_support.js" defer></script>
    <!-- ... -->
</head>

Android 平台支持

确保在 AndroidManifest.xml 文件中添加 android:usesCleartextTraffic="true"

<application
    android:name=".Application"
    android:label="bos_gateway_viewer_example"
    android:icon="@mipmap/ic_launcher"
    android:usesCleartextTraffic="true"
    ...
>
    ...
</application>

iOS 平台支持

Info.plist 文件中添加以下键值对:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

完整示例代码

example/lib/main.dart

import 'package:bos_gateway_viewer/bos_gateway_viewer.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
        appBarTheme: AppBarTheme(
          backgroundColor: Theme.of(context).colorScheme.primary,
          foregroundColor: Theme.of(context).colorScheme.onPrimary,
          surfaceTintColor: Colors.transparent,
          elevation: 0,
        ),
      ),
      routes: {
        '/': (context) => const HomeScreen(),
        BosGatewatWidgetPreviewScreen.routeName: (context) =>
            const BosGatewatWidgetPreviewScreen(),
      },
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  [@override](/user/override)
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final _formKey = GlobalKey<FormState>();
  final Map<String, dynamic> widgetSettings = {"network": NearNetwork.mainnet};

  bool generateFucntionalKeyLoading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('初始化屏幕'),
      ),
      body: SingleChildScrollView(
        child: SizedBox(
          width: double.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Form(
                autovalidateMode: AutovalidateMode.onUserInteraction,
                key: _formKey,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: Column(
                    children: [
                      const SizedBox(height: 15),
                      const Text("小部件设置",
                          style: TextStyle(fontSize: 20)),
                      const SizedBox(height: 10),
                      TextFormField(
                        initialValue: "vlmoon.near/widget/ProfileEditor",
                        decoration: inputDecoration('小部件源'),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入小部件源';
                          }
                          return null;
                        },
                        onSaved: (newValue) {
                          widgetSettings["widgetSrc"] = newValue!;
                        },
                      ),
                      const SizedBox(height: 15),
                      TextFormField(
                        initialValue: '{}',
                        decoration: inputDecoration("小部件属性"),
                        onSaved: (newValue) {
                          final widgetPropsEncoded = """'$newValue'""";
                          widgetSettings["widgetProps"] = widgetPropsEncoded;
                        },
                      ),
                      const SizedBox(height: 15),
                      const Text(
                        "NEAR 账户(如果需要匿名认证,可以留空)",
                        style: TextStyle(fontSize: 20),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 10),
                      Row(
                        children: [
                          const Text("网络类型",
                              style: TextStyle(fontSize: 16)),
                          const Spacer(),
                          DropdownButton<NearNetwork>(
                            value: widgetSettings["network"],
                            items: NearNetwork.values
                                .map((e) => DropdownMenuItem(
                                      value: e,
                                      child: Text(e.name),
                                    ))
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                widgetSettings["network"] = value!;
                              });
                            },
                          ),
                        ],
                      ),
                      const SizedBox(height: 15),
                      TextFormField(
                        initialValue: "bosmobile.near",
                        decoration: inputDecoration("账户 ID"),
                        onSaved: (newValue) {
                          widgetSettings["accountId"] = newValue;
                        },
                      ),
                      const SizedBox(height: 15),
                      TextFormField(
                        initialValue:
                            "ed25519:5tbP6myFeFztTaCk25E8XkXeMvmxeUL9T4cJppKhSnFJsPA9NYBzPhu9eNMCVC9KBhTkKk6s8bGyGG28dUczSJ7v",
                        decoration: inputDecoration("私钥"),
                        onSaved: (newValue) {
                          widgetSettings["privateKey"] = newValue;
                        },
                      ),
                      const SizedBox(height: 15),
                      TextFormField(
                        initialValue: "1",
                        decoration: inputDecoration("NEAR 允许金额"),
                        keyboardType: TextInputType.number,
                        onSaved: (newValue) {
                          widgetSettings["allowance"] = newValue;
                        },
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 15),
              if (!generateFucntionalKeyLoading)
                ElevatedButton(
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();
                      if (widgetSettings["privateKey"] != "" &&
                          widgetSettings["accountId"] != "" &&
                          widgetSettings["allowance"] != "") {
                        Navigator.of(context).pushNamed(
                          BosGatewatWidgetPreviewScreen.routeName,
                          arguments: widgetSettings,
                        );
                      }
                    }
                  },
                  child: const Text("打开 BosGatewayWidget"),
                )
              else
                const CircularProgressIndicator(),
            ],
          ),
        ),
      ),
    );
  }

  InputDecoration inputDecoration(String labelText) {
    return InputDecoration(
      floatingLabelBehavior: FloatingLabelBehavior.always,
      border: const OutlineInputBorder(),
      labelText: labelText,
      labelStyle: const TextStyle(fontSize: 20),
    );
  }
}

class BosGatewatWidgetPreviewScreen extends StatelessWidget {
  const BosGatewatWidgetPreviewScreen({super.key});

  static const routeName = '/bos_gateway_widget_preview_screen';

  [@override](/user/override)
  Widget build(BuildContext context) {
    final bosGatewaySettings =
        ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;

    return Scaffold(
        appBar: AppBar(
          title: const Text('BosGatewayWidgetPreview'),
        ),
        body: BosGatewayWidget(
          nearAuthCreds: NearAuthCreds(
            network: bosGatewaySettings["network"],
            accountId: bosGatewaySettings["accountId"],
            privateKey: bosGatewaySettings["privateKey"],
          ),
          widgetSettings: WidgetSettings(
            widgetSrc: bosGatewaySettings["widgetSrc"],
            widgetProps: bosGatewaySettings["widgetProps"],
          ),
          onError: (errorMessage) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(errorMessage),
              ),
            );
          },
        )
        // body: BosGatewayWidget(
        //   nearAuthCreds: NearAuthCreds(
        //     network: NearNetwork.mainnet,
        //     accountId: "bosmobile.near",
        //     privateKey:
        //         "ed25519:5tbP6myFeFztTaCk25E8XkXeMvmxeUL9T4cJppKhSnFJsPA9NYBzPhu9eNMCVC9KBhTkKk6s8bGyGG28dUczSJ7v",
        //   ),
        //   widgetSettings: WidgetSettings(
        //     widgetSrc: "devgovgigs.near/widget/Post",
        //     widgetProps: "{}",
        //   ),
        // ),
        );
  }
}

更多关于Flutter BOS网关查看插件bos_gateway_viewer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter BOS网关查看插件bos_gateway_viewer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


bos_gateway_viewer 是一个用于查看和管理 Flutter 应用中 BOS(Blockchain Operating System)网关的插件。通过这个插件,开发者可以方便地监控和管理与 BOS 网关相关的操作。以下是如何使用 bos_gateway_viewer 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 bos_gateway_viewer 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  bos_gateway_viewer: ^版本号

请将 ^版本号 替换为你想要使用的 bos_gateway_viewer 插件的实际版本号。

2. 导入插件

在你的 Dart 文件中导入 bos_gateway_viewer 插件。

import 'package:bos_gateway_viewer/bos_gateway_viewer.dart';

3. 初始化插件

在应用的 main 函数中初始化 bos_gateway_viewer 插件。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 BOS Gateway Viewer
  await BosGatewayViewer.initialize();

  runApp(MyApp());
}

4. 使用插件

你可以在应用中的任何地方使用 bos_gateway_viewer 插件来查看和管理 BOS 网关。以下是一个简单的示例,展示了如何使用 BosGatewayViewer 来显示网关信息。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('BOS Gateway Viewer Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 显示 BOS 网关信息
              await BosGatewayViewer.showGatewayInfo(context);
            },
            child: Text('Show Gateway Info'),
          ),
        ),
      ),
    );
  }
}

5. 自定义配置

bos_gateway_viewer 插件可能提供了一些自定义配置选项,你可以根据需要对其进行配置。例如,设置网关的 URL 或其他参数。

await BosGatewayViewer.setGatewayUrl('https://your-gateway-url.com');

6. 处理回调

如果插件提供了回调功能,你可以通过监听回调来处理特定的网关事件。

BosGatewayViewer.onGatewayEvent.listen((event) {
  print('Gateway Event: $event');
});

7. 清理资源

在应用退出时,确保清理 bos_gateway_viewer 插件占用的资源。

@override
void dispose() {
  BosGatewayViewer.dispose();
  super.dispose();
}

8. 调试和日志

bos_gateway_viewer 插件可能提供了调试和日志功能,你可以启用这些功能来帮助调试。

BosGatewayViewer.enableDebugLogging(true);
回到顶部