微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在颤动中获取后列表视图消失

如何解决在颤动中获取后列表视图消失

我使用 Firebase 作为后端,出于某种原因,每当我从 firestore 获取数据时,在这个小部件中,列表视图都会出现一秒钟然后消失,直到我按下底部应用栏中的配置文件图标,然后它就在那里。如果我在小部件之间切换,它会再次消失,所以我必须再次按下下面的图标才能显示它。

这是错误的 gif:
https://i.imgur.com/UkyV0wJ.gif

我正在使用提供程序,当我实现这个列表视图时,我在控制台中注意到了这个错误
无法加载 providerinstaller 模块:找不到可接受的模块。本地版本为0,远程版本为0。
我确实在我的 Home Widget 中做了同样的事情,它运行良好,从提供者到类内部的设置,我确保我的所有数据都被正确接收并且没有发生 Firebase 异常。
这是我的代码的工作原理:

class _ProfileState extends State<Profile> {
 @override
  void initState() {
    UserPostNotifier userPostNotifier =
        Provider.of<UserPostNotifier>(context,listen: false);
    DatabaseServices()
        .getUserPosts(FirebaseAuth.instance.currentUser.uid,userPostNotifier);
    super.initState();
  }
...
...
@override
  Widget build(BuildContext context) {
    UserPostNotifier userPostNotifier = Provider.of<UserPostNotifier>(context);
...
Scaffold and stuff here
...
ListView.builder(
    itemBuilder: (BuildContext context,int index) {
      return ProfilePost(
        content: userPostNotifier.userPostList[index].content,areCommentsAllowed:
            userPostNotifier.userPostList[index].areCommentsAllowed,index: index,);
    },itemCount: userPostNotifier.userPostList.length,)

这是我的通知程序类:

class UserPostNotifier with ChangeNotifier {
  
  List<UserPost> _userPostList = [];
  UserPost _currentUserPost;

  UnmodifiableListView<UserPost> get userPostList =>
      UnmodifiableListView(_userPostList);

  set userPostList(List<UserPost> userPostList) {
    _userPostList = userPostList;
    notifyListeners();
  }

  set currentUserPost(UserPost userPost) {
    _currentUserPost = userPost;
    notifyListeners();
  }

  UserPost get currentUserPost => _currentUserPost;
}

我也以这种方式将提供者添加到我的多重提供者中:
ChangeNotifierProvider<UserPostNotifier>(
      create: (context) => UserPostNotifier(),),

解决方法

从我可以通过您输入的代码识别出的信息,您有:

Widget build(BuildContext context) {
    UserPostNotifier userPostNotifier = ....

这意味着每次重建小部件树时,都会创建一个新的 UserPostNotifier 实例并将其分配给 userPostNotifier,这就是您的问题。

在不了解代码的情况下,一个快速的解决方案是在开始时声明 userPostNotifier,然后在构建器中测试变量是否为空,如果是,则进行赋值。

class _ProfileState extends State<Profile> {
UserPostNotifier? userPostNotifier;

....

@override
  Widget build(BuildContext context) {
    if (userPostNotifier == null) {
        userPostNotifier = Provider.of<UserPostNotifier>(context);
    }

那样你将始终使用相同的实例...我认为在 initState 中使用不同的实例并不理想。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。