Ask Your Question
3

How can user input be obtained and inserted into the SQLite database using Flutter?

asked 2022-04-05 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-05-17 11:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-04-05 11:00:00 +0000

Seen: 12 times

Last updated: May 17 '22