【问题标题】:Provider not updating custom widget when value changes值更改时提供程序不更新自定义小部件
【发布时间】:2021-11-22 12:02:50
【问题描述】:

我的提供程序在一个自定义小部件内使用,该小部件在父小部件内用作ListTile

提供程序位于stream 内部,从Firebase database 获取数据,当触发流时,它将新数据存储在提供程序内部作为Map

提供者称为LastMessageMap 称为messageMap,使用函数updateMap 添加新数据:

var messageInstance = Provider.of<global.LastMessage>(context, listen: false);
StreamSubscription<Event> updates;

// roomId is a string that is used as a key
updates = ref.child(RoomId).onChildAdded.listen((event) async{ // the stream works correctly and the new data gets stored 
      String _x = await getLastMessage();// a function that gets the data from the database 
      messageInstance.updateMap(RoomId, _x);
    });
class LastMessage extends ChangeNotifier{
  Map<String, String> messageMap = {};

  void updateMap(String RoomID, String lastMessage){
    messageMap[RoomID] = lastMessage;
    notifyListeners();
  }

现在的问题是,即使在 messageMap 更新后,当 listen 设置为 false 时,小部件也不会重建,尽管它在 listentrue 时有效,但它使整个应用程序很慢

【问题讨论】:

    标签: flutter dart flutter-provider


    【解决方案1】:

    只有当监听器为真时,小部件才会被重建。 如果 listener 为 false,则调用 notifyListeners() 时不会重建小部件;

    【讨论】:

    • 情况并非如此,因为我使用了类似的东西来更新ListView,即使listen 设置为false@StasVo 也能正常工作
    • 监听的错误值,专门用于防止提供商更新小部件。如果您将在您的小部件已使用 False 值更新时提供案例代码,我将尝试解释为什么会发生这种情况。
    • 实际上是一个简单的代码,我在问题中提到的自定义小部件有一个List,它被称为Contact。我以与上面相同的方式使用listen: false 引用提供程序,在呈现ListView 的小部件中有List = instance.contactList,然后使用ListView 显示列表,并且当使用a 将新元素添加到列表中时我调用notifyListeners() 的提供程序内部的函数,ListView 被重建。如果你不明白到底发生了什么,我会尝试使用 github @StasVo 分享更多项目
    • 我还要注意我使用ListView.builder@StasVo
    • 我觉得github上的分享代码会更好理解。
    【解决方案2】:

    解决方案是使用 StreamBuilder 而不是提供程序来更新小部件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-13
      • 2021-08-17
      • 2020-11-23
      • 2021-04-26
      • 2015-04-22
      • 1970-01-01
      • 2021-10-12
      • 2020-10-07
      相关资源
      最近更新 更多