I'm a bit stuck on getting the "conn" variable into "insertregistration" so that I only write the connection to the database once and not repeat it for every query.

import 'dart:async';
import 'package:mysql1/mysql1.dart';

class Database {
  MySqlConnection conn;
  connection() async {
       conn = await MySqlConnection.connect(ConnectionSettings(
        host: 'x',
        port: x,
        user: 'x',
        db: 'x',
        password: 'x'));
  }

  dynamic insertregistration(String username, String password, String email, String nome, String nascita) async {

    conn = connection().conn;
    var result = await conn.query('insert into user (username,password,email,nome,nascita,iscrizione) values (?, ?, ?, ?, ?, ?)', ['$username', '$password', '$email', '$nome', '$nascita', '2020-10-21']);

    await conn.close();
}
}

This was one of my many tried solutions, but obviously it doesn't work

How can I do? Thanks in advance :)


Solution 1: Maxi Malvido

I would suggest to transform the Database class into a Singleton.

To solve your problem you need to call connection and await for it, then do the query.

  dynamic insertregistration(String username, String password, String email, String nome, String nascita) async {
    await this.connection();

    var result = await conn.query('insert into user (username,password,email,nome,nascita,iscrizione) values (?, ?, ?, ?, ?, ?)', ['$username', '$password', '$email', '$nome', '$nascita', '2020-10-21']);

    await conn.close();
  }

For the singleton implementation, I would go with something like this:

import 'dart:async';
import 'package:mysql1/mysql1.dart';

class Database {

  MySqlConnection conn;

  Database._privateConstructor() {
  }

  static final Database instance = Database._privateConstructor();

  Future<void> initConnection() async {
       this.conn = await MySqlConnection.connect(ConnectionSettings(
        host: 'x',
        port: x,
        user: 'x',
        db: 'x',
        password: 'x'));
  }

  dynamic insertregistration(String username, String password, String email, String nome, String nascita) async {

    await this.initConnection();

    var result = await this.conn.query(
      'insert into user (username,password,email,nome,nascita,iscrizione) values (?, ?, ?, ?, ?, ?)',
      ['$username', '$password', '$email', '$nome', '$nascita', '2020-10-21']
    );

    await conn.close();
  }
}

And to use the singleton you will use it like this:

Database.instance.insertRegistration(sername, password, email, nome, nascita);