Last active
December 26, 2024 13:40
-
-
Save ayoubzulfiqar/ea0c22461075ce708a2abbca433a9744 to your computer and use it in GitHub Desktop.
SQFlite on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Logic | |
import 'dart:math'; | |
import 'package:sqflite_common_ffi/sqflite_ffi.dart'; | |
class SQLiteHelper { | |
Database? _database; | |
Future<Database> get database async { | |
if (_database != null) { | |
return _database!; | |
} | |
_database = await initWinDB(); | |
return _database!; | |
} | |
Future<Database> initWinDB() async { | |
sqfliteFfiInit(); | |
final databaseFactory = databaseFactoryFfi; | |
return await databaseFactory.openDatabase( | |
inMemoryDatabasePath, | |
options: OpenDatabaseOptions( | |
onCreate: _onCreate, | |
version: 1, | |
), | |
); | |
} | |
// Platform Specific | |
Future<Database> initDB() async { | |
if (Platform.isWindows || Platform.isLinux) { | |
sqfliteFfiInit(); | |
final databaseFactory = databaseFactoryFfi; | |
final appDocumentsDir = await getApplicationDocumentsDirectory(); | |
final dbPath = join(appDocumentsDir.path, "databases", "data.db"); | |
final winLinuxDB = await databaseFactory.openDatabase( | |
dbPath, | |
options: OpenDatabaseOptions( | |
version: 1, | |
onCreate: _onCreate, | |
), | |
); | |
return winLinuxDB; | |
} else if (Platform.isAndroid || Platform.isIOS || Platform.isMacOS) { | |
final documentsDirectory = await getApplicationDocumentsDirectory(); | |
final path = join(documentsDirectory.path, "data.db"); | |
final iOSAndroidDB = await openDatabase( | |
path, | |
version: 1, | |
onCreate: _onCreate, | |
); | |
return iOSAndroidDB; | |
} | |
throw Exception("Unsupported platform"); | |
} | |
Future<void> _onCreate(Database database, int version) async { | |
final db = database; | |
await db.execute(""" CREATE TABLE IF NOT EXISTS users( | |
id INTEGER PRIMARY KEY, | |
name TEXT, | |
email TEXT, | |
password INTEGER, | |
phoneNumber INTEGER | |
) | |
"""); | |
} | |
Future<User> insertUSer(User user) async { | |
final db = await database; | |
db.insert( | |
"users", | |
user.toMap(), | |
conflictAlgorithm: ConflictAlgorithm.replace, | |
); | |
return user; | |
} | |
Future<List<User>> batchInsert() async { | |
final db = await database; | |
final batch = db.batch(); | |
final Random random = Random(); | |
final List<User> userList = List.generate( | |
1000, | |
(index) => User( | |
id: index + 1, | |
name: 'User $index', | |
email: '[email protected]', | |
password: random.nextInt(9999), | |
phoneNumber: random.nextInt(10000), | |
), | |
); | |
for (final User user in userList) { | |
batch.insert( | |
'users', | |
user.toMap(), | |
conflictAlgorithm: ConflictAlgorithm.replace, | |
); | |
} | |
await batch.commit(); | |
return userList; | |
} | |
Future<List<User>> getAllUsers() async { | |
final db = await database; | |
final List<Map<String, dynamic>> maps = await db.query('users'); | |
return List.generate(maps.length, (index) { | |
return User( | |
id: maps[index]['id'], | |
name: maps[index]['name'], | |
email: maps[index]['email'], | |
password: maps[index]['password'], | |
phoneNumber: maps[index]['phoneNumber'], | |
); | |
}); | |
} | |
Future<User?> getUserById(int userId) async { | |
final db = await database; | |
final List<Map<String, dynamic>> maps = await db.query( | |
'users', | |
where: 'id = ?', | |
whereArgs: [userId], | |
); | |
if (maps.isNotEmpty) { | |
return User( | |
id: maps[0]['id'], | |
name: maps[0]['name'], | |
email: maps[0]['email'], | |
password: maps[0]['password'], | |
phoneNumber: maps[0]['phoneNumber'], | |
); | |
} | |
return null; | |
} | |
Future<void> deleteAllUsers() async { | |
final db = await database; | |
final Batch batch = db.batch(); | |
batch.delete('users'); | |
await batch.commit(); | |
} | |
} | |
// UI | |
import 'package:flutter/material.dart'; | |
class Home extends StatefulWidget { | |
const Home({super.key}); | |
@override | |
State<Home> createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
final SQLiteHelper helper = SQLiteHelper(); | |
@override | |
void initState() { | |
super.initState(); | |
WidgetsFlutterBinding.ensureInitialized(); | |
helper.initWinDB(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
backgroundColor: Colors.white, | |
leading: TextButton( | |
onPressed: () async { | |
await helper.batchInsert(); | |
setState(() {}); | |
}, | |
child: const Text("ADD"), | |
), | |
actions: [ | |
TextButton( | |
onPressed: () async { | |
await helper.deleteAllUsers(); | |
setState(() {}); | |
}, | |
child: const Text("DEL"), | |
), | |
]), | |
body: FutureBuilder<List<User>>( | |
future: helper.getAllUsers(), | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.waiting) { | |
return const Center(child: CircularProgressIndicator()); | |
} else if (snapshot.hasError) { | |
return Center(child: Text('Error: ${snapshot.error}')); | |
} else if (!snapshot.hasData || snapshot.data!.isEmpty) { | |
return const Center(child: Text('No users found.')); | |
} else { | |
final users = snapshot.data!; | |
return ListView.builder( | |
itemCount: users.length, | |
itemBuilder: (context, index) { | |
final user = users[index]; | |
return gradientCardSample(user, context); | |
}, | |
); | |
} | |
}, | |
), | |
); | |
} | |
} | |
Widget gradientCardSample(User user, BuildContext context) { | |
return Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: Card( | |
child: Padding( | |
padding: const EdgeInsets.all(20), | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.start, | |
crossAxisAlignment: CrossAxisAlignment.start, | |
children: [ | |
Text( | |
"ID: ${user.id}", | |
style: const TextStyle( | |
fontSize: 20, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
Text( | |
"Name: ${user.name}", | |
style: const TextStyle( | |
fontSize: 20, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
Text( | |
"Email: ${user.email}", | |
style: const TextStyle( | |
fontSize: 15, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
Text( | |
"Phone Number: ${user.phoneNumber}", | |
style: const TextStyle( | |
fontSize: 15, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
Text( | |
"Password: ${user.password}", | |
style: const TextStyle( | |
fontSize: 15, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
// Main | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const App()); | |
} | |
class App extends StatelessWidget { | |
const App({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Home(), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment