Flutter banner

Prerequisites

Before you start, make sure you:

1

Add HTTP Package

dart pub add http
2

Configure database credentials

Get the database URL.

turso db show --url <database-name>

Get the database authentication token.

turso db tokens create <database-name>

Pass the credentials to the flutter app by using the --dart-define flags:

flutter run --debug \
  --dart-define=TURSO_URL="..." \
  --dart-define=TURSO_AUTH_TOKEN="..."

Make sure that the TURSO_URL passed above should be modified to use the https protocol instead of libsql. (e.g “https://[db-name].turso.io”)

3

Execute SQL

lib/main.dart
import 'package:http/http.dart' as http;

const String tursoDbUrl =
    String.fromEnvironment("TURSO_URL", defaultValue: "");
const String tursoAuthToken =
    String.fromEnvironment("TURSO_AUTH_TOKEN", defaultValue: "");

late Future<List<T>> itemResults;

Future<List<T>> getItems() async {
  final response = await http.post(Uri.parse(tursoDbUrl),
      headers: {
        HttpHeaders.authorizationHeader: "Bearer $tursoAuthToken",
        HttpHeaders.acceptHeader: "application/json"
      },
      body: json.encode({
        "statements": ["select * from table_name"]
      }));

  var itemList = List<T>.from(jsonDecode(response.body)[0]["results"]
          ["rows"]
      .map((dynamic item) => item[0]));
  return itemList;
}

itemResults = getItems();

Examples