To obtain and insert user input into an SQLite database using Flutter, you can follow these steps:
import 'package:sqflite/sqflite.dart';
Future<Database> database = openDatabase(
join(await getDatabasesPath(), 'database.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE my_table(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
);
},
version: 1,
);
This code will create a new database file named database.db and create a table called my_table.
Future<void> insertData(String name, int age) async {
// Get a reference to the database.
final Database db = await database;
// Insert the data into the correct table.
await db.insert(
'my_table',
{'name': name, 'age': age},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
The function expects two parameters: name and age. It will insert these values into the my_table table in the database.
final nameController = TextEditingController();
final ageController = TextEditingController();
...
ElevatedButton(
onPressed: () {
String name = nameController.text;
int age = int.tryParse(ageController.text);
if (name != null && age != null) {
insertData(name, age);
}
},
child: Text('Insert Data'),
),
TextField(
controller: nameController,
decoration: InputDecoration(
labelText: 'Name',
),
),
TextField(
controller: ageController,
decoration: InputDecoration(
labelText: 'Age',
),
keyboardType: TextInputType.number,
),
In this code, we create two text fields and an elevated button. The text fields are controlled by two TextEditingController objects. When the button is pressed, the user input is retrieved from the text fields, and the insertData function is called with the name and age values as parameters. If the data is successfully inserted into the database, it will replace any existing row with the same ID.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-05 11:00:00 +0000
Seen: 12 times
Last updated: May 17 '22
How can the total number of records in a table be calculated using Flutter SQFLite?
How can zooming similar to desktop be achieved in HTML webview browser using Flutter?
In what way can the appleID signin be utilized in flutter?
How to maintain state across different pages using flutter?
How can I change a CameraImage Stream into bytes or a file in Flutter?
How can the current page context be obtained by a Flutter GetX controller?