0

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?

2 Answers 2

2

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());

Sign up to request clarification or add additional context in comments.

Comments

-1

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?

1 Comment

there is nothing wrong with using provider inside the build method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.