Garrett
Garrett

Reputation: 1792

Flutter conditional widget but {} not equal {}

I am trying to conditionally build a widget in Flutter, however my condition somehow doesn't equal what I think it should. How is this not the same thing?

Provider

class User with ChangeNotifier {
  Map _user = {};

  Map get user {
    return _user;
  }

  void setUser() {
    // Set _user and notify listeners
  }
}

Widget doing the build

Widget build(BuildContext context) {
    final user = Provider.of<User>(context);

    if (user.user == {}) {
      print('It equals it');
      print(user.user);
    } else {
      print('It DOES NOT equals it');
      print(user.user);
    }

    ...

    bottomNavigationBar: user.user == {} ? BottomNavBar() : null
}

Here is what that somehow comes out to: enter image description here

What am I doing wrong?

Upvotes: 0

Views: 1142

Answers (2)

Larry McKenzie
Larry McKenzie

Reputation: 3283

In short you think these are equal but they are not. Collections in Dart have no inherent equality. Two sets are not equal, even if they contain exactly the same objects as elements.

There is a package for dealing with this: https://pub.dev/packages/collection

It forces you to specify the type of equality you want to apply to keys and values.

Example: const MapEquality(const IdentityEquality(), const ListEquality());

Upvotes: 2

Traufvihal
Traufvihal

Reputation: 64

It is not recommended to use the provider inside the build method. Check this guide for help

Also you should clarify if the widget is stateful or stateless and you should post the code of the setUser() method.

That said, where (and when) are you calling the setter of user?

Upvotes: -1

Related Questions