Home > Software engineering >  List becomes empty when the control reaches to build in Flutter?
List becomes empty when the control reaches to build in Flutter?

Time:04-06

void main() => runApp( MaterialApp(
      home:  HomePage(),
    ));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() =>  _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController controller = TextEditingController();

  // Get json result and convert it to model. Then add
  Future<Null> getUserDetails() async {
    final response = await http.get(Uri.parse(url));
    final responseJson = json.decode(response.body);

    setState(() {
      for (Map user in responseJson) {
        Map<String, dynamic> _userDetails =
            user.map((key, value) => MapEntry(key, value?.toString()));

        _userDetails.addAll(_userDetails);

        print("fdsfsd: ");
        print(_userDetails.length);
      }
    });
  }

  @override
  void initState() {
    super.initState();

    getUserDetails();
  }

Till this point things do work fine. The print statement shows the good length of the list.

When this needs to go in the GUI through build, there suddenly the list becomes empty:

This print statement results 0. I have removed the extra code for clarity sake.

 @override
  Widget build(BuildContext context) {
    print("FFFF: ");
    print(_userDetails.length);

    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
        elevation: 0.0,
      ),
      body: Column(
        children: <Widget>[
          Container(
      ..........
  }

Rest of the code is here:

List<UserDetails> _searchResult = [];
List<UserDetails> _userDetails = [];

final String url = 'https://jsonplaceholder.typicode.com/users';

class UserDetails {
  final int? id;
  final String? firstName, lastName, profileUrl;

  UserDetails(
      {this.id,
      this.firstName,
      this.lastName,
      this.profileUrl =
          'https://i.amz.mshcdn.com/3NbrfEiECotKyhcUhgPJHbrL7zM=/950x534/filters:quality(90)/2014/06/02/c0/zuckheadsho.a33d0.jpg'});

  factory UserDetails.fromJson(Map<String, dynamic> json) {
    return UserDetails(
      id: json['id'],
      firstName: json['name'],
      lastName: json['username'],
    );
  }
}

CodePudding user response:

You are doing

_userDetails.addAll(_userDetails);

this will add _userDetails to itself.

It might help to write it as

this._userDetails.addAll(_userDetails);

so it gets added to the right one. But personally I would suggest to use 2 different names. Like leave the underscore at the local one, like

    Map<String, dynamic> userDetails =
        user.map((key, value) => MapEntry(key, value?.toString()));

    _userDetails.addAll(userDetails);

EDIT:

I realize that this also won't work because you actually want UserDetail objects in there, so I think this is what you want:

  for (Map user in responseJson) {
    _userDetails.add(UserDetails.fromJson(user);
  }

EDIT2:

Since user is of type Map<dynamic, dynamic> instead of Map<String, dynamic>, this:

factory UserDetails.fromJson(Map<String, dynamic> json)

needs to be changed to

factory UserDetails.fromJson(Map<dynamic, dynamic> json)

as well

  • Related