0
votes

The question seems to be a little dumb, but as someone who never worked with async functions before it is not so trivial.

I fetch some json data from http request and build a list. For example, lets say userid and username.

[
  {"userid":1,"username":"JohnDoe"},
  {"userid":2,"username":"SamSmith"}
]

Code:

Future<UsersList> fetchUsers() async {
  final response = await http.get(
      Uri.encodeFull('https://www.myurl.com/users'),
      headers: {'Accept': 'application/json'});

  if (response.statusCode == 200) {
    return UsersList.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load users');
  }
}

class User {
  final String userid;
  final String username;
  String tag;

  User({this.userid, this.username});

  factory User.fromJson(Map<String, dynamic> json){
    return User(
      userid: json['userid'],
      username: json['username'],
    );
  }
}

class UsersList {
  final List<User> Users;

  UsersList({this.Users});

  factory UsersList.fromJson(List<dynamic> parsedJson) {
    List<User> Users = new List<User>();
    Users = parsedJson.map((i) => User.fromJson(i)).toList();
    return new UsersList(Users: Users);
  }
}

class UsersTab extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return UsersTabState();
  }
}

class UsersTabState extends State<UsersTab> {
  Future<UsersList> Users;

  @override
  void initState() {
    super.initState();
    Users = fetchUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('users'), backgroundColor: Colors.blue),
      body: Center(
        child: FutureBuilder<usersList>(
          future: users,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.users.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Text('User: ' +
                        snapshot.data.users[index].username +
                        '\nTag: ' + 
                        snapshot.data.users[index].tag),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

Now, I also have local data from shared_preferences where I can tag users by id. So I have a function like

Future<String> getTag(String id) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(id) ?? "none";
}

My question is, where can I call this function? It obviously must be before the FutureBuilder builds the list but after http request has finished. I had some ideas like initState of UsersTabState or User class constructor but it always ends up in a future somewhere where I would need a String. What is the best way to get the locally stored tag into the User class?

1

1 Answers

0
votes

So my solution is to put the getTag method inside the User class and make both User.fromJson and UsersList.fromJson into static methods which returns Future<User> and Future<UsersList>. By doing that, we can put all the awaiting into fetchUsers so this method will end up returning a UsersList object which are done after awaiting it.

Future<UsersList> fetchUsers() async {
  final response = await http.get(
      Uri.encodeFull('https://www.myurl.com/users'),
      headers: {'Accept': 'application/json'});

  if (response.statusCode == 200) {
    return await UsersList.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load users');
  }
}

class User {
  final String userid;
  final String username;
  final String tag;

  User({this.userid, this.username, this.tag});

  static Future<User> fromJson(Map<String, dynamic> json) async {
    final userId = json['userid'];
    final tag = await _getTag(userId);

    return User(
      userid: json['userid'],
      username: json['username'],
      tag: tag
    );
  }

  static Future<String> _getTag(String id) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(id) ?? "none";
  }
}

class UsersList {
  final List<User> Users;

  UsersList({this.Users});

  static fromJson(List<dynamic> parsedJson) async {
    List<User> Users = new List<User>();
    Users = await Future.wait(parsedJson.map((i) => User.fromJson(i));
    return new UsersList(Users: Users);
  }
}

class UsersTab extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return UsersTabState();
  }
}

class UsersTabState extends State<UsersTab> {
  Future<UsersList> Users;

  @override
  void initState() {
    super.initState();
    Users = fetchUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('users'), backgroundColor: Colors.blue),
      body: Center(
        child: FutureBuilder<usersList>(
          future: users,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.users.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Text('User: ' +
                        snapshot.data.users[index].username +
                        '\nTag: ' +
                        snapshot.data.users[index].tag),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

One trick I have used is this to await on multiple Future's which will return a List:

    Users = await Future.wait(parsedJson.map((i) => User.fromJson(i));

You can read about it here: https://api.dart.dev/stable/2.7.2/dart-async/Future/wait.html