Skip to content
Advertisement

Creating Flutter Web Server that connects to an SQL server

I want to create a Flutter web server that has an SQL connection. Just like in PHP we can connect to the SQL server like this:

// 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();

So I’m looking for the equivalent of the above code in Flutter.

I found a documentation about how to make the Flutter Web Server here: https://dart.dev/tutorials/server/httpserver

But when I’m trying to find a solution about “how to connect the Flutter web server to SQL”. All I found are Flutter apps to SQL which is not what I’m looking for. Is it even possible to create a Flutter Web Server with SQL connection?

Note: I’m not trying to make Flutter Web Client.

Advertisement

Answer

You can basically make a HTTP server on your phone with something like this:

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();
}

Now for all the sql handling you can use whatever there is for Dart and Flutter clients like sqflite. You don’t need to use libraries specifically made for Server side dart since the job that needs to be done is the same.

You can run Flutter web on your browser with 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 that are specifically designed to be a backend framework. hope that helps.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement