'Fetch Data from an API and save in an sqlite database Flutter Dart Android

I have a insertUser method that works fine when i click a button or trigger it another way. I have a fetchUser method that fetches users data from an API. I call the fetch method in initState to fetch the data as soon as the app launches and that is also working fine. In my fetchUser method, i loop through the data collected, pass it to a user object and save in a database. I am able to create user objects for each user but cant save it in the database. Here is my code.

 Future<List<User>> fetchUser() async {
    final response =
    await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
    if (response.statusCode == 200) {
      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();

      parsed.forEach((entry) {
        String name = entry["name"];
        String username = entry["username"];
        String passcode = entry["username"];
        print("id: $name, username: $username, passcode: $passcode");

        var newUser = User(
          name: name,
          username: username,
          passcode: name,
        );

        print(newUser.passcode);
        UserDatabase.instance.insertUser(user);  //this is not working

      });

      return parsed.map<User>((json) => User.fromMapp(json)).toList();

      // return parsed.map<User>((json) => User.fromMap(json)).toList();
    } else {
      throw Exception('Failed to load users');
    }
  }

The insert method

  insertUser(User user) async{
    Database db = await instance.database;
    return  await db.insert(_table_field_agents, user.toUserMap(),conflictAlgorithm: ConflictAlgorithm.ignore
    );
  }

I call fetchUser in initState, everything works alright except saving the data to the database.



Sources

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

Source: Stack Overflow

Solution Source