Search code examples
jsonfluttervariablessqflite

Flutter/Dart - How to pass variables between classes?


I am very new to programming and I am trying to pass a variable (jsonData) from a future to another future in a different class, so the data from the variable can be stored in a database. Dont be confused, I am using an API for getting the neccessary data, this works perfectly fine. Any tips how I can access the variable jsonData to insert the data?

//first class gets the json data
class getJSONData {

Future<void> makeRequest() async {
var url = "some url";

Map inputData = {
  "Password": example,
  "SQL": sql query,
  "db_server": "server",
  "db_table": "table",
};

var body = json.encode(inputData);

var putRequest = await http.put(
    Uri.encodeFull(url), headers: {"Content-Type": "application/json"},
    body: body);

//this variable has to be stored
var jsonData = json.decode(putRequest.body);
  }
}


//data needs to be inserted here

class Database {

Future<void> insertJSON() async {
db = await openDatabase(
  join(await getDatabasesPath(), tableName),
  onCreate: (db, version) {
    return db.execute('''
     INSERT INTO $tableName(column1, column2, etc) VALUES (${jsonData["Records].data1}, ${jsonData["Records].data2}, etc)
     ''');
     }
   );
 }
}

Solution

  • You have many options. I'll suggest you one. Change the signatures of both methods.
    Example

    Your HttpClient class

    Future<Map<String, dynamic>> makeRequest() async {
        // ... your code
        var jsonData = json.decode(putRequest.body);
        return jsonData;
    }
    

    Your DB Class

        Future<void> insertJSON(Map<String, dynamic> jsonData) async {
            db = await openDatabase(
            join(await getDatabasesPath(), tableName),
            onCreate: (db, version) {
            return db.execute('''
               INSERT INTO $tableName(column1, column2, etc) VALUES 
                (${jsonData["Records].data1}, ${jsonData["Records].data2}, etc)
              ''');
         }
       );
     }
    

    Use a third Class/object/method that make the call to the api, take the result and pass it to the db class:

    main() async {
        HttClient http = HttpClient();
        Database db = Database();
        final json = await http.makeRequest();
        await db.insertJSON(json);
    }