Flutter IPFS服务器集成插件ipfs_server的使用

发布于 1周前 作者 yibo5220 来自 Flutter

Flutter IPFS服务器集成插件ipfs_server的使用

一个支持在移动端使用IPFS服务节点的Flutter插件。目前仅支持Android端。

Demo主页

Android

在项目 build.gradle 文件下的 allprojects 下的 repositories 下加入以下代码:

flatDir {
    dirs project(":ipfs_server").file("libs")
}

APIs

开启IPFS

Future<bool?> openIPFS()

关闭IPFS

Future<bool?> closeIPFS()

当前节点信息

Future<String?> getCurrentIdInfo()

通过CID获取本地IPFS文件连接

Future<String?> getUrlByCID({required String cid})

上传一个文件到IPFS,返回CID

Future<String?> uploadFileToIPFS({required String filePath})

添加节点

Future<bool?> addNode({required String nodeUrl})

移除节点

Future<bool?> removeNode({required String nodeUrl})

节点列表

Future<List<String>?> nodeList()

示例代码

以下是完整的示例代码,展示了如何使用 ipfs_server 插件进行基本操作。

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:ipfs_server/ipfs_server.dart';

void main() {
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _outputInfo = "";

  String _platformVersion = 'Unknown';
  final _ipfsServerPlugin = IpfsServer();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _ipfsServerPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('IPFS Server 插件示例'),
        ),
        body: ListView(
          children: [
            Text(
              _platformVersion,
              style: const TextStyle(
                fontSize: 20,
              ),
            ),
            Wrap(
              children: [
                TextButton(
                  onPressed: () async {
                    bool? isOpen = await IpfsServer().openIPFS();

                    debugPrint("isOpen: $isOpen");

                    if (isOpen == true) {
                      setState(() {
                        _outputInfo = "节点已开启";
                      });
                    }
                  },
                  child: const Text(
                    '开启IPFS',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    bool? isClose = await IpfsServer().closeIPFS();

                    debugPrint("isClose: $isClose");

                    if (isClose == true) {
                      setState(() {
                        _outputInfo = "节点已关闭";
                      });
                    }
                  },
                  child: const Text(
                    '关闭IPFS',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    String? idInfo = await IpfsServer().getCurrentIdInfo();

                    debugPrint("idInfo: $idInfo");

                    if (idInfo != null) {
                      setState(() {
                        _outputInfo = idInfo;
                      });
                    }
                  },
                  child: const Text(
                    '本机节点信息',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    List<String>? nodeList = await IpfsServer().nodeList();

                    setState(() {
                      _outputInfo = nodeList?.join("   ") ?? "";
                    });

                    debugPrint("nodeList Size: ${nodeList?.length ?? 0}");

                    nodeList?.forEach((element) {
                      debugPrint("node: $element");
                    });
                  },
                  child: const Text(
                    '连接节点列表',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    final nodeUrls = [
                      "/ip4/47.108.163.105/tcp/4001/p2p/12D3KooWHxqszCwHaBpVzEJaqcYHUAUMUGB9i3182Tbb4NXMr66Q",
                      // "/ip4/47.108.163.105/udp/4001/quic-v1/p2p/12D3KooWHxqszCwHaBpVzEJaqcYHUAUMUGB9i3182Tbb4NXMr66Q",
                      // "/ip4/47.108.163.105/tcp/4001/p2p/12D3KooWHxqszCwHaBpVzEJaqcYHUAUMUGB9i3182Tbb4NXMr66Q",
                      // "/ip4/47.108.163.105/udp/4001/quic-v1/p2p/12D3KooWHxqszCwHaBpVzEJaqcYHUAUMUGB9i3182Tbb4NXMr66Q",
                    ];

                    for (var nodeUrl in nodeUrls) {
                      bool? isSuccess = await IpfsServer().addNode(nodeUrl: nodeUrl);

                      if (isSuccess == true) {
                        setState(() {
                          _outputInfo = "连接点:$nodeUrl 添加成功";
                        });
                      } else {
                        setState(() {
                          _outputInfo = "连接点:$nodeUrl 添加失败";
                        });
                      }

                      debugPrint(_outputInfo);
                    }
                  },
                  child: const Text(
                    '添加连接点',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    FilePickerResult? result = await FilePicker.platform.pickFiles();
                    String? path = result?.files.single.path;

                    if (path != null) {
                      setState(() {
                        _outputInfo = "文件上传中";
                      });
                      String? cid = await IpfsServer().uploadFileToIPFS(filePath: path);
                      if (cid != null) {
                        setState(() {
                          _outputInfo = "文件上传成功 - $cid";
                        });

                        debugPrint(_outputInfo);
                      } else {
                        setState(() {
                          _outputInfo = "文件上传失败";
                        });
                      }
                    }
                  },
                  child: const Text(
                    '上传文件',
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    const cid = "QmaQv15U6eBMoewELbedimGjTQoo33QgQZtyVVjnADW79k";

                    String? url = await IpfsServer().getUrlByCID(cid: cid);

                    setState(() {
                      _outputInfo = url ?? "";
                    });

                    debugPrint("连接地址:$_outputInfo");
                  },
                  child: const Text(
                    '通过CID获取访问地址',
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 20,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 20,
              ),
              child: SelectableText(
                _outputInfo,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter IPFS服务器集成插件ipfs_server的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter IPFS服务器集成插件ipfs_server的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中集成IPFS(InterPlanetary File System)服务器,你可以使用 ipfs_server 插件。这个插件允许你在Flutter应用中与IPFS节点进行交互,上传和下载文件,以及管理IPFS网络中的数据。

以下是如何在Flutter项目中使用 ipfs_server 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  ipfs_server: ^0.1.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化IPFS服务器

在你的Flutter应用中,你需要初始化IPFS服务器。通常,你可以在 main.dart 文件中进行初始化。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化IPFS服务器
  await IpfsServer.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter IPFS Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 使用IPFS服务器

在你的应用页面中,你可以使用 IpfsServer 类来与IPFS节点进行交互。以下是一个简单的示例,展示如何上传和下载文件。

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

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _fileHash = '';
  String _downloadedContent = '';

  Future<void> _uploadFile() async {
    // 假设你有一个文件路径
    String filePath = 'path/to/your/file.txt';

    // 上传文件到IPFS
    String fileHash = await IpfsServer.addFile(filePath);
    setState(() {
      _fileHash = fileHash;
    });
  }

  Future<void> _downloadFile() async {
    // 下载文件从IPFS
    String content = await IpfsServer.catFile(_fileHash);
    setState(() {
      _downloadedContent = content;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter IPFS Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('File Hash: $_fileHash'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _uploadFile,
              child: Text('Upload File to IPFS'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _downloadFile,
              child: Text('Download File from IPFS'),
            ),
            SizedBox(height: 20),
            Text('Downloaded Content: $_downloadedContent'),
          ],
        ),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!