'Empty map on flutter when initiating


Map user = {};

  Future<void> getUser(String idProfile) async {
    final response = await ac.getItem("/v2/users/:0", [idProfile]);
    if (response.statusCode >= 200 && response.statusCode < 300) {
      setState(() {
        user = json.decode(response.body);
        print(user);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getUser(getCurrentUser());
    print(user);
  }

With the first print, it returns me the user. However, at the second doesn't. I need to get the user information. How could I do it?



Solution 1:[1]

  Map user = {};

//Return a user from the function
  Future<Map<String, dynamic>> getUser(String idProfile) async {
    final response = await ac.getItem("/v2/users/:0", [idProfile]);
    if (response.statusCode >= 200 && response.statusCode < 300) {
        user = json.decode(response.body) as Map<String, dynamic>;
        return user
  
    }
    else {
      throw Exception();
    }
  }
// Set the user value in initstate 
  @override
  void initState() {
    super.initState();
    user = getUser(getCurrentUser());
    print(user);
  }

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Vipin Kumar Kashyap