'Sending Flutter form data into an SQLite database

I am a new Flutter developer trying to figure out how to send my form data into SQLite as an instance of a simple class I set up.

I am trying to create a new user in my SQLite database, by capturing the values from each form field, saving them and then sending a new User class instance to the database with those values.

Below is my dart.main file.

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'package:path/path.dart';
import 'database_helper.dart';
import 'user.dart';

void main() async {
  runApp(MyApp());
  var databasesPath = await getDatabasesPath();
  String path = join(databasesPath, 'v1.db');

  Database database = await openDatabase(path, version: 1,
      onCreate: (Database db, int version) async {
        // When creating the db, create the table
        await db.execute(
            'CREATE TABLE users (id INTEGER PRIMARY KEY, firstName TEXT, lastName TEXT, userName TEXT, password TEXT, score INTEGER, email TEXT)');
      });
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          fontFamily: 'Roboto',
        ),
        home: Scaffold(
            appBar: AppBar(
              title: const Text("Sleppytime"),
            ),
            body: Center(
                child: Padding(
                    padding: EdgeInsets.all(20.0),
                    child: ListView(
                        children: [
                      Container(
                          width: 300,
                          child: Center(
                              child: Align(
                                  alignment: Alignment.center,
                                  child: Text(
                                    "Do you have trouble sleeping no matter what you do?",
                                    style:
                                        Theme.of(context).textTheme.headline4,
                                  )))),
                      Container(
                          width: 300,
                          child: Center(
                              child: Align(
                                  alignment: Alignment.center,
                                  child: MyCustomForm()
                              ))
                      )
                    ])))));
  }
}

class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Define a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the
  // Form widget and allows validation of the form.
  //
  // Note: This is a `GlobalKey<FormState>`,
  //       not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();

  // For listening to FormField changes, like onChanged
  final userNameListener = TextEditingController();
  final firstNameListener = TextEditingController();
  final lastNameListener = TextEditingController();
  final passwordListener = TextEditingController();

  @override
  void initState() {
    super.initState();
    // Start listening to changes.
    firstNameListener.addListener(_storeFormField);
    lastNameListener.addListener(_storeFormField);
    userNameListener.addListener(_storeFormField);
    passwordListener.addListener(_storeFormField);
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    firstNameListener.dispose();
    lastNameListener.dispose();
    userNameListener.dispose();
    passwordListener.dispose();
    super.dispose();
  }

  _storeFormField() {
  }

  void _saveForm() {
    if(_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
    }
  }


  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            // The validator receives the text that the user has entered.
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter your first name';
                }
                return null;
              },
              onSaved: (value) => new User().firstName = value,
              controller: firstNameListener,
              autofocus: true,
              decoration: InputDecoration(
                hintText: 'First name',
              )
          ),
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your last name';
              }
              return null;
            },
            onSaved: (value) => new User().lastName = value,
            controller: lastNameListener,
            decoration: InputDecoration(
              hintText: 'Last name',
            ),
          ),
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter a username';
              }
              return null;
            },
            onSaved: (value) => new User().userName = value,
            controller: userNameListener,
            decoration: InputDecoration(
              hintText: 'Username',
            ),
          ),
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter a password';
              }
              return null;
            },
            onSaved: (value) => new User().password = value,
            controller: passwordListener,
            decoration: InputDecoration(
              hintText: 'Password',
            ),
            obscureText: true,
          ),
          ElevatedButton(
            onPressed: () {
              _saveForm();
              User.insertUser(User());
            },
            child: Text('Submit'),
          ),
        ],
      ),

    );
  }
}

And my User class:

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'package:path/path.dart';
export 'user.dart';

class User {
  final int? id;
  String? firstName;
  String? lastName;
  String? userName;
  String? password;
  int? score;
  final String? email;

  User({
    this.id,
    this.firstName,
    this.lastName,
    this.userName,
    this.password,
    this.score,
    this.email,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'firstName': firstName,
      'lastName': lastName,
      'userName': userName,
      'password': password,
      'score': score,
      'email': email
    };
  }

  @override
  String toString() {
    return 'User{id: $id, firstName: $firstName, lastName: $lastName, userName: $userName, password: $password, score: $score, email: $email}';
  }

  static Future<void> insertUser(User user) async {
    final db = await openDatabase('v1.db');
    await db.insert(
      'users',
      user.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }
}

It looks like data is being passed to my database, but all the fields are 'null', so I'm not sending the values properly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source