Changing user preferences in a flutter app when navigating to new screen

Viewed 85

I have 2 screens in my flutter app and they're defined as follows:

  1. allFriends: has a list of users on cards, which when clicked on will bring up a full view of the user (otherUserProfileView).

  2. otherUserProfileView: shows the profile view (information is loaded from a Firebase Realtime Database)

When I navigate to otherUserProfileView, I still see content about the user that I first viewed after reloading.

Do you know how I can fix this so I can see a new user each time I navigate to otherUserProfileView, after clicking a new user? Any help is appreciated.

Below is the code:

allFriends:

child: InkWell(
        onTap: (){
          Navigator.of(context).push(MaterialPageRoute(
            builder: (context) =>
                Screen2(
                  friendID: friend.userID,
                  friendName: friend.name,
                  profilePic: friend.picture,
                ),
          ));
        },
        child: Card()
)

otherUserProfileView:

class OtherUserProfileView extends StatefulWidget {
  final String friendID;
  final String friendName;
  final String profilePic;

  const OtherUserProfileView(
      {Key? key,
        required this.friendID,
        required this.friendName,
        required this.profilePic})
      : super(key: key);

  @override
  _OtherUserProfileViewState createState() => _OtherUserProfileViewState();
}

class _OtherUserProfileViewState extends State<OtherUserProfileView> {
  List<String> images = [];
  StreamSubscription? _imagesStream;

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

  void addImages() {
    images.add(widget.profilePic);

    final db = FirebaseDatabase.instance
        .ref()
        .child('users')
        .child(widget.friendID)
        .child("pictures");
    _imagesStream = db.onValue.listen((event) {
      if (event.snapshot.exists) {
        final data = new Map<dynamic, dynamic>.from(
            event.snapshot.value as Map<dynamic, dynamic>);

        data.forEach((key, value) {
          db.child(key).onValue.listen((event) {
            setState(() {
              images.add(value);
            });
          });
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      body: _getContent(),
    );
  }

  Widget _getContent() {
    return new ListView(
      scrollDirection: Axis.vertical,
      children: <Widget>[
        CardRow(friendID: widget.friendID),
        images == null
            ? Container()
            : Column(
              children: [
                Container(
                  height: 200,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    shrinkWrap: true,
                    itemBuilder: (context, index) =>
                        BuildPicture(images[index]),
                    itemCount: images.length,
                  ),
                ),
              ],
            ),
      ],
    );
  }

  @override
  void deactivate() {
    _imagesStream?.cancel();
    super.deactivate();
  }
}

class BuildPicture extends StatelessWidget {
  final String url;

  BuildPicture(this.url);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: Image.network(url),
    );
  }
}

class CardRow extends StatefulWidget {
  final String friendID;

  const CardRow({Key? key, required this.friendID}) : super(key: key);

  @override
  State<CardRow> createState() => _CardRowState();
}

class _CardRowState extends State<CardRow> {
  late StreamSubscription _userStream;
  late StreamSubscription _friendsStream;

  static String uid = "";
  static DatabaseReference userDatabase =
  FirebaseDatabase.instance.ref().child('users').child("$uid");

  static List<String> theirFriends = [];

  var _userName = "";
  var _emailAddress = "";
  var _country = "";
  var _bio = "";
  var _profileUrl;
  var user;
  int mutualFriends = theirFriends.length;

  @override
  void initState() {
    super.initState();
    uid = widget.friendID;
    _activateListeners();
    _retrieveFriends();
  }

  void _activateListeners() {
    _userStream = userDatabase.onValue.listen((event) {
      if (event.snapshot.exists) {
        final data = new Map<dynamic, dynamic>.from(
            event.snapshot.value as Map<dynamic, dynamic>);

        final username = data['username'] as String;
        final emailAdd = data['emailAdd'] as String;
        final country = data['country'] as String;
        final bio = data['bio'] as String;
        final profilePicUrl = data['profilePicUrl'] as String;

        setState(() {
          _userName = username;
          _emailAddress = emailAdd;
          _country = country;
          _bio = bio;
          _profileUrl = profilePicUrl;
        });
      }
    });
  }

  void _retrieveFriends() {
    final friendsDb = FirebaseDatabase.instance
        .ref()
        .child('users')
        .child(uid)
        .child("friends");
    _friendsStream = friendsDb.onValue.listen((event) {
      if (event.snapshot.exists) {
        final data = new Map<dynamic, dynamic>.from(
            event.snapshot.value as Map<dynamic, dynamic>);

        theirFriends.clear();
        data.forEach((key, value) {
          friendsDb.child(key).onValue.listen((event) {
            final acc = new Map<dynamic, dynamic>.from(
                event.snapshot.value as Map<dynamic, dynamic>);
            final userID = acc['userID'] as String;

            theirFriends.add(userID);
          });
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return userCardContent();
  }

  Container userCardContent() {
    return new Container(
      child: ClipOval(
        child: SizedBox(
            width: 110,
            height: 110,
            child: (_profileUrl != null)
                ? Image.network(_profileUrl, fit: BoxFit.cover)
                : Image.asset(
              'assets/Blank-Avatar.png',
              fit: BoxFit.cover,
            )),
      ),
    );
  }

  @override
  void deactivate() {
    _userStream.cancel();
    _friendsStream.cancel();
    super.deactivate();
  }
}
1 Answers

Even though the id that was being used was correct, one of the subclasses wasn't being updated so the id that was being used was the wrong one

To find the cause of this, I traced it by printing the id wherever I needed to use it.

Related