Skip to content

Commit db1677d

Browse files
committed
Add Flutter database and storage Answers document
1 parent ce72a8d commit db1677d

File tree

4 files changed

+362
-51
lines changed

4 files changed

+362
-51
lines changed
Lines changed: 338 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,338 @@
1+
# Flutter Database And Storage: Answers
2+
3+
1. **What is SQLite, and how is it used in Flutter?**
4+
- SQLite is a lightweight, serverless database engine that supports SQL-based querying. In Flutter, it's often used for local storage, enabling the app to store data locally on the user's device. The `sqflite` package is commonly used to integrate SQLite into Flutter apps.
5+
6+
2. **How do you integrate the sqflite package into a Flutter project?**
7+
- Add `sqflite` to the `pubspec.yaml` file:
8+
9+
```yaml
10+
dependencies:
11+
sqflite: ^x.x.x
12+
```
13+
14+
- Then, import and initialize the database in your Dart code:
15+
16+
```dart
17+
import 'package:sqflite/sqflite.dart';
18+
import 'package:path/path.dart';
19+
20+
Future<Database> initDatabase() async {
21+
return openDatabase(
22+
join(await getDatabasesPath(), 'my_database.db'),
23+
onCreate: (db, version) {
24+
return db.execute(
25+
'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)',
26+
);
27+
},
28+
version: 1,
29+
);
30+
}
31+
```
32+
33+
3. **What is Hive, and how does it differ from SQLite?**
34+
- Hive is a lightweight, NoSQL key-value database designed for fast, local storage without needing complex SQL queries. Unlike SQLite, which uses SQL syntax, Hive stores data in binary format and is highly optimized for mobile use, offering simpler CRUD operations.
35+
36+
4. **How do you perform CRUD operations with sqflite?**
37+
- **Create**:
38+
39+
```dart
40+
await db.insert('users', {'id': 1, 'name': 'John Doe'});
41+
```
42+
43+
- **Read**:
44+
45+
```dart
46+
final List<Map<String, dynamic>> users = await db.query('users');
47+
```
48+
49+
- **Update**:
50+
51+
```dart
52+
await db.update('users', {'name': 'Jane Doe'}, where: 'id = ?', whereArgs: [1]);
53+
```
54+
55+
- **Delete**:
56+
57+
```dart
58+
await db.delete('users', where: 'id = ?', whereArgs: [1]);
59+
```
60+
61+
5. **What is Moor, and how does it enhance SQLite usage?**
62+
- Moor is a persistence library for Flutter apps that simplifies SQLite operations with a higher-level API. It generates type-safe queries, supports complex queries, and provides reactive streams to observe changes in the database.
63+
64+
6. **How do you manage data migrations in SQLite?**
65+
- Migrations can be handled by defining a new schema version and providing `onUpgrade` and `onDowngrade` callbacks in the `openDatabase` method:
66+
67+
```dart
68+
openDatabase(
69+
'my_database.db',
70+
version: 2,
71+
onUpgrade: (db, oldVersion, newVersion) {
72+
if (oldVersion < 2) {
73+
db.execute('ALTER TABLE users ADD COLUMN age INTEGER');
74+
}
75+
},
76+
);
77+
```
78+
79+
7. **What is SharedPreferences, and when would you use it?**
80+
- `SharedPreferences` is a Flutter plugin that allows you to store key-value pairs of primitive data types (such as strings, integers, booleans) locally. It is best used for lightweight, non-relational data like user settings or app preferences.
81+
82+
8. **How do you implement local storage with SharedPreferences?**
83+
- First, add the package:
84+
85+
```yaml
86+
dependencies:
87+
shared_preferences: ^x.x.x
88+
```
89+
90+
- Then, store and retrieve data:
91+
92+
```dart
93+
final prefs = await SharedPreferences.getInstance();
94+
await prefs.setString('username', 'JohnDoe');
95+
96+
final username = prefs.getString('username');
97+
```
98+
99+
9. **What is Isar, and how does it differ from other databases?**
100+
- Isar is an extremely fast NoSQL database for Flutter that supports complex queries and indexes with minimal overhead. It provides native support for Flutter and Dart with a developer-friendly API and performs much faster than SQLite and Hive.
101+
102+
10. **How do you store images in a database using Flutter?**
103+
- Images are often stored as binary data (BLOB) in a SQLite database:
104+
105+
```dart
106+
Uint8List imageBytes = await imageFile.readAsBytes();
107+
await db.insert('images', {'image': imageBytes});
108+
```
109+
110+
11. **What is the path_provider package, and how is it used?**
111+
- `path_provider` is a Flutter package that provides a platform-specific way to access commonly used file system paths (such as the documents directory). It is often used to store files, such as images or database files.
112+
113+
```dart
114+
final directory = await getApplicationDocumentsDirectory();
115+
```
116+
117+
12. **How do you implement data encryption with Hive?**
118+
- Hive supports AES-256 encryption natively. When opening a Hive box, pass a secure encryption key:
119+
120+
```dart
121+
var encryptionKey = Hive.generateSecureKey();
122+
var box = await Hive.openBox('secureBox', encryptionCipher: HiveAesCipher(encryptionKey));
123+
```
124+
125+
13. **What is ObjectBox, and how does it work with Flutter?**
126+
- ObjectBox is a high-performance NoSQL database optimized for fast local storage with native Dart support. It uses object-oriented programming (OOP) principles, allowing Flutter developers to work with actual Dart objects.
127+
128+
14. **How do you create a database schema using Moor?**
129+
- Define tables and fields using Dart classes:
130+
131+
```dart
132+
class Users extends Table {
133+
IntColumn get id => integer().autoIncrement()();
134+
TextColumn get name => text()();
135+
}
136+
```
137+
138+
15. **What is the moor_generator package, and how does it simplify database operations?**
139+
- `moor_generator` automatically generates code for database operations such as table creation, queries, and data insertion, reducing boilerplate and ensuring type safety.
140+
141+
16. **How do you implement lazy loading with a database?**
142+
- Lazy loading can be achieved by fetching a limited number of records at a time (pagination) and loading more as the user scrolls.
143+
144+
```dart
145+
final users = await db.query('users', limit: 10, offset: currentPage * 10);
146+
```
147+
148+
17. **What is Riverpod, and how does it work with local storage?**
149+
- Riverpod is a state management library for Flutter. It can be integrated with local storage systems like Hive or SQLite to manage and synchronize the state between the database and UI components in a reactive manner.
150+
151+
18. **How do you perform complex queries with Moor?**
152+
- Moor supports complex queries such as joins, aggregations, and custom SQL statements:
153+
154+
```dart
155+
final query = select(users).join([
156+
leftOuterJoin(posts, posts.userId.equalsExp(users.id)),
157+
]);
158+
```
159+
160+
19. **What is the json_serializable package, and how does it help with database storage?**
161+
- `json_serializable` automatically generates code for converting Dart objects to and from JSON. It simplifies storing objects in databases by making it easy to serialize and deserialize objects for storage.
162+
163+
20. **How do you create a search function with SQLite?**
164+
- Implement a search query using `LIKE`:
165+
166+
```dart
167+
final results = await db.query('users', where: 'name LIKE ?', whereArgs: ['%searchQuery%']);
168+
```
169+
170+
21. **What is the role of BLoC pattern in database operations?**
171+
- The BLoC (Business Logic Component) pattern separates business logic from the UI, making database interactions more structured and scalable by handling events and streams in a clean, testable way.
172+
173+
22. **How do you handle multiple database instances in Flutter?**
174+
- Multiple database instances can be handled by opening and managing separate database connections or using multi-database packages like Isar and ObjectBox, which support multiple boxes/collections.
175+
176+
23. **What is drift, and how does it differ from Moor?**
177+
- Drift is the new name for Moor. It provides a more modern API and a rebranding to clarify its purpose as a reactive persistence library for Dart and Flutter.
178+
179+
24. **How do you implement data caching in Flutter?**
180+
- Data caching can be implemented using local storage solutions like `Hive`, `SQLite`, or `SharedPreferences` to cache data retrieved from a server or API, reducing network calls and improving performance.
181+
182+
25. **What is the sqlite3 package, and how is it used in Flutter?**
183+
- The `sqlite3` package is a Dart package providing direct access to SQLite databases. It's often used in Flutter apps for more granular control over SQLite, compared to higher-level packages like `sqflite`.
184+
185+
26. **How do you create relationships between tables in SQLite?**
186+
- Create relationships using foreign keys:
187+
188+
```sql
189+
CREATE TABLE orders (
190+
id INTEGER PRIMARY KEY,
191+
userId INTEGER,
192+
FOREIGN KEY (userId) REFERENCES users(id)
193+
);
194+
```
195+
196+
27. **What is the role of Dio in network requests with databases?**
197+
- `Dio` is a powerful HTTP client for Dart. When working with databases, it can be used to fetch data from APIs, which can then be stored locally for offline access or syncing with remote databases.
198+
199+
28. **How do you use ObjectBox for reactive programming?**
200+
- ObjectBox provides real-time reactive data streams. You can subscribe to changes in the database and update the UI automatically when data changes.
201+
202+
29. **What is data serialization, and why is it important in databases?**
203+
- Data serialization is the process of converting data objects into a format (such as JSON or binary) that can be stored or transmitted. In databases, it is crucial for saving complex data types like objects or lists.
204+
205+
30. **How do you implement pagination with a local database?**
206+
- Implement pagination by loading a subset of data at a time using `LIMIT` and `OFFSET` in SQL queries:
207+
208+
```sql
209+
SELECT * FROM users LIMIT 10 OFFSET 20;
210+
```
211+
212+
31. **What is the floor package, and how does it work in Flutter?**
213+
- `Floor` is a persistence library that abstracts SQLite. It uses annotation-based code generation to simplify database interactions with Flutter.
214+
215+
32. **How do you manage database connections efficiently?**
216+
- Use a singleton pattern to ensure a single instance of the database connection is used throughout the app:
217+
218+
```dart
219+
class DatabaseHelper {
220+
static final DatabaseHelper _instance = DatabaseHelper._internal();
221+
DatabaseHelper._internal();
222+
factory DatabaseHelper() => _instance;
223+
}
224+
```
225+
226+
33. **What is DataTable, and how is it used to display database data?**
227+
- `DataTable` is a Flutter widget used to display tabular data. It is useful for showing data retrieved from a local or remote database in a structured format.
228+
229+
```dart
230+
DataTable(columns: [...], rows: [...]);
231+
```
232+
233+
34. **How do you implement sorting and filtering with a database?**
234+
- Sorting can be implemented by using the `ORDER BY` clause, and filtering can be done using `WHERE` clauses in SQL queries:
235+
236+
```sql
237+
SELECT * FROM users WHERE age > 25 ORDER BY name ASC;
238+
```
239+
240+
35. **What is encrypt, and how is it used for secure data storage?**
241+
- The `encrypt` package provides encryption algorithms (e.g., AES) that can be used to encrypt sensitive data before storing it in a local database.
242+
243+
```dart
244+
final key = Key.fromUtf8('my 32 length key');
245+
final encrypter = Encrypter(AES(key));
246+
final encrypted = encrypter.encrypt('Sensitive data');
247+
```
248+
249+
36. **How do you handle asynchronous database queries?**
250+
- Use `async` and `await` to perform non-blocking database operations in Flutter:
251+
252+
```dart
253+
Future<List<Map<String, dynamic>>> getUsers() async {
254+
final db = await database;
255+
return db.query('users');
256+
}
257+
```
258+
259+
37. **What is the moor_ffi package, and how does it help with SQLite?**
260+
- `moor_ffi` is a package that provides a faster implementation of SQLite for Flutter, using native bindings for improved performance, especially in desktop and mobile environments.
261+
262+
38. **How do you integrate Firebase Firestore with Flutter for data storage?**
263+
- Add the Firestore package:
264+
265+
```yaml
266+
dependencies:
267+
cloud_firestore: ^x.x.x
268+
```
269+
270+
- Then, interact with Firestore:
271+
272+
```dart
273+
FirebaseFirestore.instance.collection('users').add({'name': 'John Doe'});
274+
```
275+
276+
39. **What is Redux pattern, and how does it work with databases?**
277+
- Redux is a state management pattern that centralizes the app state in a single store. It can work with databases by dispatching actions to read/write data, updating the global state, and reacting to changes in the UI.
278+
279+
40. **How do you implement data validation before saving to the database?**
280+
- Validate input data using Dart or a package like `formz` before saving it to the database to ensure that only valid data is stored.
281+
282+
41. **What is Stream in the context of local databases?**
283+
- In local databases like SQLite, a `Stream` is used to reactively listen for changes in data and automatically update the UI when the data changes.
284+
285+
42. **How do you create a model class for database operations?**
286+
- Define a Dart class that mirrors the database table:
287+
288+
```dart
289+
class User {
290+
final int id;
291+
final String name;
292+
293+
User({required this.id, required this.name});
294+
295+
Map<String, dynamic> toMap() {
296+
return {'id': id, 'name': name};
297+
}
298+
}
299+
```
300+
301+
43. **What is the importance of indexing in databases?**
302+
- Indexing improves the speed of data retrieval operations in a database by creating pointers to data, but it can also slow down write operations.
303+
304+
44. **How do you implement foreign key constraints in SQLite?**
305+
- Foreign keys can be enforced in SQLite using the `FOREIGN KEY` clause when defining a table:
306+
307+
```sql
308+
CREATE TABLE orders (
309+
id INTEGER PRIMARY KEY,
310+
userId INTEGER,
311+
FOREIGN KEY (userId) REFERENCES users(id)
312+
);
313+
```
314+
315+
45. **What is drift in the context of Flutter, and how is it used?**
316+
- Drift (previously Moor) is a persistence library that provides a reactive database layer. It simplifies database operations, type-safe queries, and synchronizes the UI with the database in Flutter.
317+
318+
46. **How do you export and import data from a database?**
319+
- Export data by serializing it into a JSON or CSV format, then save it to a file. Importing involves parsing the file and inserting data into the database.
320+
321+
47. **What is BlocListener, and how does it work with database events?**
322+
- `BlocListener` is a widget in the BLoC pattern that listens to state changes. It can be used to react to database events, such as showing a message when data is saved successfully.
323+
324+
48. **How do you manage database transactions in Flutter?**
325+
- Use `transaction` in SQLite to ensure multiple database operations execute atomically:
326+
327+
```dart
328+
await db.transaction((txn) async {
329+
await txn.insert('users', {'name': 'John Doe'});
330+
await txn.insert('orders', {'userId': 1, 'product': 'Laptop'});
331+
});
332+
```
333+
334+
49. **What is DatabaseHelper, and how is it structured?**
335+
- `DatabaseHelper` is a singleton class pattern that provides methods to open, close, and manage a database connection in Flutter. It centralizes all database operations in one place.
336+
337+
50. **How do you test database operations in a Flutter app?**
338+
- Use unit tests to mock database interactions. The `mockito` package can help in mocking `sqflite` or `moor` operations for testing purposes without relying on actual database reads/writes.

Flutter/Database_And_Storage/questions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# Flutter Database And Storage: Questions
2+
13
1. What is SQLite, and how is it used in Flutter?
24
2. How do you integrate the sqflite package into a Flutter project?
35
3. What is Hive, and how does it differ from SQLite?

Flutter/StateManagement/questions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# Flutter State Management: Questions
2+
13
1. What is state management, and why is it important in Flutter?
24
2. Explain the difference between local state and global state.
35
3. How do you manage state using the setState method?

0 commit comments

Comments
 (0)