Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain and insert user input into an SQLite database using Flutter, you can follow these steps:

  1. Import the SQLite package:

import 'package:sqflite/sqflite.dart';

  1. Open the database:
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.

  1. Create a function to insert data into the database:
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.

  1. Get user input and call the insertData function:
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.