我的Flutter 应用程序中有两个屏幕,它们的定义如下:

  1. allFriends:卡片上有一个用户列表,点击该列表将显示用户的完整视图(otherUserProfileView).

  2. otherUserProfileView:显示纵断面图(信息从Firebase实时数据库加载)

当我导航到otherUserProfileView时,我仍然会看到关于我在重新加载后第一次查看的用户的内容.

你知道我该怎么解决这个问题吗?这样每次我在点击一个新用户后导航到otherUserProfileView时都能看到一个新用户?感谢您的帮助.

代码如下:

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

推荐答案

尽管使用的id是正确的,但其中一个子类没有更新,因此使用的id是错误的

为了找到原因,我通过在需要的地方打印id来追踪它.

Flutter相关问答推荐

Flutter日期和时间 Select 器未显示

类型flatter doctor get zsh:未找到命令:macO中flatter

在Riverpod ConsumerWidget中使用文本编辑控制器

如何在WidgetRef引用外部的函数中使用Riverpod刷新数据

在Ffltter中,我已经使用了Ffltter_BLOC Cupit和Pusher,但当获得新数据时,UI没有更新

如何将小部件代码移动到另一个文件以获得更好的可读性

Flutter CarouselSlider中如何防止右图与放大的中心图重叠?

自定义类提供程序 Riverpod Flutter 中的可变变量

Flutter:在 pubspec.yaml 中找不到assets资源

运行任何 flutter 命令都会显示无法安装 <版本>

在 Flutter 中从 FireStore 获取数据并编译它们需要太多时间

Flutter 中的区域不匹配

如何将此文本按钮剪辑在堆栈中的圆形头像上方?

如何(部分)更新 riverpod 中的 AsyncValue?

应用程序包含嵌入式私钥或密钥库文件

Android Electric eel Mac M1:运行 flutter doctor -v 时无法找到Bundle 的 java 版本

仅使用 Flutter 在本地环境中托管 Web 服务器

如何将变量翻译成其他语言

Flutter Firestore 数据库排序最近 24 小时内最喜欢的文档

解密 Modulr 安全令牌