在VS Code中使用Flutter时,我看不到也无法访问我的PostgreSQL数据库

移动开发 2026-07-09

我想把Flutter代码(那个会自动出现的代码)连接到PostgreSQL数据库。

因此我想通过我在pub.dev上发现的这个包 postgres 来访问PostgreSQL。

main.dart:

import 'package:postgres/postgres.dart';

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

  final conn = await Connection.open(
    Endpoint(
      host: 'localhost',
      database: 'postgres',
      username: 'postgres',
      password: 'LRm9@a',
    )
  );
}

pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  postgres: ^3.5.10
  cupertino_icons: ^1.0.8

其他部分保持不变。我仍然可以在Google上运行我的应用,但它不起作用:

应用外观

并且我遇到了一个错误:

错误截图

如果我没有初始化 'conn',就没有错误。

我不明白为什么会找不到这样的文件。

解决方案

localhost 很可能是问题所在。

如果你在Chrome浏览器或模拟器上运行Flutter,localhost 并不会指向你的PostgreSQL服务器。

尝试替换:

host: 'localhost'

为:

host: '127.0.0.1',

port: 5432,

或者如果使用Android模拟器:

host: '10.0.2.2'

另外,确保PostgreSQL正在运行并在端口5432接受TCP连接。

还有一点:直接从Flutter连接PostgreSQL通常不推荐。通常Flutter连接到后端API,由后端连接PostgreSQL。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章