💾 MySQL Database Setup
Flint Dart supports MySQL natively. You can connect automatically using environment variables, or override with DB.connect()
for full control.
1️⃣ Environment Setup
Add your database credentials to a .env
file to enable automatic connections:
DB_CONNECTION='mysql'
DB_HOST="localhost"
DB_PORT=3306
DB_USER="flint_sample"
DB_PASSWORD="flint_sample"
DB_NAME="flint_sample"
2️⃣ Auto Connect (Recommended)
In Flint Dart v1.3+, the Flint()
constructor automatically:
- Loads credentials from
.env
- Establishes a MySQL connection
- Logs connection status to the console
import 'package:flint_dart/flint_dart.dart';
void main() {
final app = Flint(autoConnectDb: true); // Auto-connects to DB, can be omitted and defaults is true
app.get('/', (req, res) => res.send('MySQL Connected!'));
app.listen(3000);
}
3️⃣ Manual Connect (Override)
To customize or avoid using .env
, call DB.connect()
manually:
await DB.connect(
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
db: 'my_database',
);
4️⃣ DB Class Reference
Flint Dart’s DB
class provides helpers for executing raw queries and managing connections. Use execute()
to run SQL or instance
to access the live connection.
5️⃣ Defining Tables and Columns
Define schema objects directly in Dart to describe tables, columns, indexes, and foreign keys:
class Table {
final String name;
final List<Column> columns;
final List<Index> indexes;
final List<ForeignKey> foreignKeys;
Table({
required this.name,
required this.columns,
this.indexes = const [],
this.foreignKeys = const [],
});
}
class Column {
final String name;
final ColumnType type;
final int length;
final bool isPrimaryKey;
final bool isAutoIncrement;
final bool isNullable;
final dynamic defaultValue;
Column({
required this.name,
required this.type,
this.isPrimaryKey = false,
this.isAutoIncrement = false,
this.isNullable = false,
this.length = 255,
this.defaultValue,
});
}
enum ColumnType {
integer, string, text, boolean, double, datetime, timestamp
}
Combine Table, Column, Index, and ForeignKey for complete schema definitions and migrations.
6️⃣ Example: User Model
A User model with table schema defined by overriding the table
getter:
class User extends Model<User> {
@override
Table get table => Table(
name: 'users',
columns: [
Column(
name: 'id',
type: ColumnType.integer,
isPrimaryKey: true,
isAutoIncrement: true,
),
Column(name: 'name', type: ColumnType.string, length: 255),
Column(name: 'email', type: ColumnType.string, length: 255),
Column(name: 'password', type: ColumnType.string),
Column(name: 'created_at', type: ColumnType.datetime, isNullable: true),
],
);
}