创建连接到 SQL 服务器的 Flutter Web 服务器

Creating Flutter Web Server that connects to an SQL server

我想创建一个具有 SQL 连接的 Flutter Web 服务器。 就像在 PHP 中一样,我们可以像这样连接到 SQL 服务器:

// Connecting to DB
$conn = new mysqli($servername, $username, $password, $dbname);

// Checking connection error
if($conn->connect_error){
   die("Connection Failed: " . $conn->connect_error);
   return;
}

// Making query
$sql = "SELECT * from $table ORDER BY updated_at ASC LIMIT $limit";

// Getting the result
$result = $conn->query($sql);

// Checking result
if($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
     $db_data[] = $row;
  }
            
  // Send back the complete records as a json
  echo json_encode($db_data);
}else{
  echo "error";
}

// Close connection
$conn->close();

所以我在 Flutter 中寻找与上述代码等效的代码。

我在此处找到了有关如何制作 Flutter Web 服务器的文档:https://dart.dev/tutorials/server/httpserver

但是当我试图找到关于“如何将 Flutter Web 服务器连接到 SQL”的解决方案时。我发现的只是 SQL 的 Flutter 应用程序,这不是我要找的。 甚至可以创建具有 SQL 连接的 Flutter Web 服务器吗?

注意:我并不是要制作 Flutter Web 客户端。

你基本上可以在你的 phone 上用这样的东西建立一个 HTTP 服务器:

void main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    4040,
  );
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    handleRequest(request);
  }
}

void handleRequest(HttpRequest request) async {
  // do your database stuff here
  request.response.write('data you got from db');
  await request.response.close();
}

现在,对于所有 sql 处理,您可以使用任何适用于 Dart 和 Flutter 客户端的东西,例如 sqflite。您不需要使用专门为服务器端 dart 创建的库,因为需要完成的工作是相同的。

您可以 运行 在浏览器上使用专门设计为后端框架的 flutter web and hence you can use it as a server but that wouldn't be a great idea since Flutter wasn't design to do that job, but a much better solution would be to use other Dart (not Flutter) frameworks like Aqueduct Flutter web。希望有帮助。