【问题标题】:Listview disappears after getting fetched in flutterListview 在颤动中被提取后消失
【发布时间】:2021-09-14 19:39:58
【问题描述】:

我使用 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(),
    ),

【问题讨论】:

    标签: firebase flutter widget provider


    【解决方案1】:

    从我可以通过您输入的代码识别的内容来看,您有:

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

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

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

    class _ProfileState extends State<Profile> {
    UserPostNotifier? userPostNotifier;
    
    ....
    
    @override
      Widget build(BuildContext context) {
        if (userPostNotifier == null) {
            userPostNotifier = Provider.of<UserPostNotifier>(context);
        }
    

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

    【讨论】:

    • 感谢您抽出宝贵时间回复。但是,我尝试了您的解决方案,但没有任何区别。我的主页提要中有同样的东西,就像我之前提到的那样,它工作得很好。如果您需要更多代码来了解发生了什么,请随时提出问题或提出任何建议。
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2015-04-27
    • 2019-03-03
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多