简体   繁体   English

导航到新屏幕时更改 flutter 应用程序中的用户首选项

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

I have 2 screens in my flutter app and they're defined as follows:我的 flutter 应用程序中有 2 个屏幕,它们的定义如下:

  1. allFriends : has a list of users on cards, which when clicked on will bring up a full view of the user ( otherUserProfileView ). allFriends :在卡片上有一个用户列表,单击它会显示用户的完整视图 ( otherUserProfileView )。

  2. otherUserProfileView : shows the profile view (information is loaded from a Firebase Realtime Database) otherUserProfileView :显示配置文件视图(信息从 Firebase 实时数据库加载)

When I navigate to otherUserProfileView , I still see content about the user that I first viewed after reloading.当我导航到otherUserProfileView时,我仍然看到有关我在重新加载后首次查看的用户的内容。

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?您知道我该如何解决这个问题,以便在单击新用户后每次导航到otherUserProfileView时都能看到新用户吗? Any help is appreciated.任何帮助表示赞赏。

Below is the code:下面是代码:

allFriends : allFriends

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

otherUserProfileView : 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();
  }
}

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即使正在使用的 id 是正确的,但其中一个子类没有被更新,所以正在使用的 id 是错误的

To find the cause of this, I traced it by printing the id wherever I needed to use it.为了找到这个原因,我通过在需要使用它的地方打印 id 来追踪它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在托管 Flutter 应用程序时出现灰屏? - Why do I get grey screen when hosting Flutter app? FirebaseMessaging:应用程序在屏幕锁定或其他应用程序打开时不显示通知 iOS Flutter - FirebaseMessaging: App not showing notification when screen is locked or some other app is open iOS Flutter 在 flutter 中通过身份验证后将用户从登录/注册页面导航到主页的正确方法 - Proper way of navigating user from login/signup page to home page after authentication in flutter 当我在 aws-amplify-react-native 中从一个屏幕导航到另一个屏幕时出现“没有当前用户” - Getting "no current user" while i am navigating from a screen to another screen in aws-amplify-react-native Flutter Firebase 消息传递:将用户发送到特定屏幕 - Flutter Firebase messaging: sending a user to a specific screen Firebase 导航到其他页面时保持用户登录 - Firebase keep user logged in when navigating to other pages Flutter FCM 推送通知在用户点击通知时显示空白屏幕 state - Flutter FCM push notification show the blank screen when user tap on Notification in killed state Flutter 应用程序有时卡在启动画面上 - Flutter app stuck sometimes on the Splash screen Flutter 发布应用程序在第一个屏幕后崩溃 - Flutter release app crashes after first screen 设置 App Check 时出现白屏 Flutter Web - White Screen while setting App Check for Flutter Web
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM