繁体   English   中英

Flutter:使用 `notifyListeners` 时,小部件不会使用 `provider` 包重新加载

[英]Flutter: Widget not reloading with `provider` package when using `notifyListeners`

我正在使用 Flutter 和 MVVM 模式和provider包构建一个聊天应用程序。 现在,我正在尝试实现屏幕以显示用户的聊天列表。

这是我的 ViewModel 类:

class ConversationsViewModel with ChangeNotifier {
  final MatchesService chatService = MatchesService();

  final String userId;

  final List<ChatCell> chatCells = [];

  ConversationsViewModel({required this.userId}) {
    loadChats();
  }

  void loadChats() async {
    final chats = await chatService.getChats(userId: userId);

    for (final chat in chats) {
      final messages = await chatService.getMessages(
        userId: userId,
        chatId: chat.chatId,
        limit: 1,
      );

      final cell = ChatCell(chat: chat, message: messages.first);
      chatCells.add(cell);

      notifyListeners();
    }
  }
}

这是我的小部件:

class Conversations extends StatefulWidget {
  const Conversations({Key? key}) : super(key: key);

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

class _ConversationsState extends State<Conversations> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Selector<ConversationsViewModel, List<ChatCell>>(
          selector: (context, vm) => vm.chatCells,
          builder: (context, chatCells, _) {
            return ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: chatCells.length,
              itemBuilder: (context, index) =>
                  Text(chatCells[index].message.message.body),
            );
          },
        )
      ],
    );
  }
}

但是,由于某种原因,即使调用了notifyListeners ,小部件也不会重新加载。

我不太确定出了什么问题,因为我遵循provider包规定的所有模式和用法。

我还尝试在initState调用loadChats ,但意识到这比在 VM 的构造函数中调用更错误。

任何帮助,将不胜感激。

您是否使用 ChangeNotifierProvider 包装了 MaterialApp?
例子:

ChangeNotifierProvider(
    create: (context) => ConversationsViewModel(),
    child: MaterialApp()
)

我认为你的问题是你没有定义你的提供者,所以你不能访问它的数据。 在您的构建方法下,您应该添加如下内容:

final conversationsProvider = Provider.of<ConversationsViewModel>(context);

然后您可以通过执行以下操作来使用它:

conversationsProvider.chatCells;

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM