You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用真机无法连接Ganache求助(模拟器运行正常)

问题描述

我正在开发一款使用Truffle框架和Ganache的Flutter应用,该应用在Android模拟器上通过10.0.2.2:7545可正常运行,但在真机上使用本地IP192.168.100.26连接时无任何响应。以下是连接Ganache的核心代码:

import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';
import 'package:web_socket_channel/io.dart';

class ContractLinking with ChangeNotifier {

   //my_IPv4_Address is 192.168.100.26

     final String _rpcUrl= Platform.isAndroid ? 'http://10.0.2.2:7545' :    'http://192.168.100.26:7545';
     final String _wsUrl = Platform.isAndroid ? 'http://10.0.2.2:7545' : 'ws://192.168.100.26:7545';

      final String _privateKey = '0x356943a0f6b475ee82a18103ad7f3a7d89bfe9c7e184f1ecdb87d758b13c064f';

      Web3Client? _web3client;
      bool isLoading = true;
      String? _abiCode;
      EthereumAddress? _contractAddress;
      Credentials? _credentials;
      DeployedContract? _contract;
      ContractFunction? _message;
      ContractFunction? _setMessage;

      String? deployedName;

      ContractLinking() {
         setup();
      }

      setup() async {
        _web3client = Web3Client(_rpcUrl, Client(), socketConnector: () {
        return IOWebSocketChannel.connect(_wsUrl).cast<String>();
        });

        await getAbi();
        await getCredentials();
        await getDeployedContract();
      }

      Future<void> getAbi() async {
        String abiStringFile =
        await rootBundle.loadString('build/contracts/HelloWorld.json');
        final jsonAbi = jsonDecode(abiStringFile);
        _abiCode = jsonEncode(jsonAbi['abi']);


        _contractAddress = EthereumAddress.fromHex(jsonAbi['networks']['5777']['address']);
      }

      Future<void> getCredentials() async {
        _credentials = EthPrivateKey.fromHex(_privateKey);
      }

      Future<void> getDeployedContract() async {
        _contract = DeployedContract(ContractAbi.fromJson(_abiCode!, "HelloWorld"), _contractAddress!);

        _message = _contract!.function("message");
        _setMessage = _contract!.function("setMessage");
        getMessage();
      }

      getMessage() async {
        final _mymessage = await _web3client!.call(contract: _contract!, function: _message!, params: []);

        deployedName = _mymessage[0];
        isLoading = false;
        notifyListeners();
      }

      setMessage(String message) async {
        isLoading = true;
        notifyListeners();
        await _web3client!.sendTransaction(_credentials!,
        Transaction.callContract(
        contract: _contract!,
        function: _setMessage!,
        parameters: [message]), chainId: 1337,
    fetchChainIdFromNetworkId: false);

        getMessage();
      }
}

现咨询如何让真机正常连接Ganache,问题是否出在RPC URL或WS URL上?


解决方案

1. 修复WebSocket URL错误

代码中Android模拟器的WS URL误用了http://协议,WebSocket必须使用ws://协议。修正后的URL配置:

final String _rpcUrl= Platform.isAndroid ? 'http://10.0.2.2:7545' : 'http://192.168.100.26:7545';
final String _wsUrl = Platform.isAndroid ? 'ws://10.0.2.2:7545' : 'ws://192.168.100.26:7545';

2. 配置Ganache允许局域网访问

打开Ganache,进入设置(右上角齿轮图标)→SERVER选项卡:

  • 将Hostname从默认的127.0.0.1改为0.0.0.0,让Ganache监听所有网络接口。
  • 确认端口保持7545,与代码中的配置一致。
  • 重启Ganache使设置生效。

3. 开放电脑防火墙端口

确保电脑防火墙没有拦截7545端口的入站请求:

  • Windows:打开Windows Defender防火墙,添加允许TCP/UDP协议7545端口的入站规则。
  • macOS:进入系统设置→网络→防火墙→选项,添加Ganache应用或手动开放7545端口。

4. 验证设备网络互通

  • 确认Android真机与运行Ganache的电脑连接在同一Wi-Fi网络下。
  • 在真机浏览器中访问http://192.168.100.26:7545,若返回类似{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"}}的响应,说明网络连通正常;若无法访问,检查IP是否正确或网络是否存在隔离。

5. 确保Chain ID一致

代码中指定了chainId: 1337,需确认Ganache的Chain ID与之匹配:

  • 进入Ganache设置→CHAIN选项卡,查看Chain ID,若不是1337则修改一致;或删除代码中的chainId参数,让web3dart自动从网络获取。

内容的提问来源于stack exchange,提问作者Abdul Hannan Faisal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:58:11