【问题标题】:Widgets get no update from the listener flutter小部件没有从侦听器颤动中获得更新
【发布时间】:2020-09-04 13:53:42
【问题描述】:

我通过以下方式实现了一个监听器:

  @override
  void didChangeDependencies() {
    final SlotDataProvider slotDevice = Provider.of<SlotDataProvider>(context);  
    spptask.streamdevice.listen((device) {
      setState(() {
        slotDevice._devices[0].name = device.name;
        print("Device data received: ${device.name} ");
      });
    }, onError: (error) {
      print("Error: $error.message");
    });

    super.didChangeDependencies();
  }

我在拆分控制器上进行监听,并调用了打印“收到的设备数据:...”,但未实现小部件。在构建方法中,我执行以下操作:

            ...
  @override
  Widget build(BuildContext context) {
    final slotProvider = Provider.of<SlotDataProvider>(context);
    final deviceProvider = Provider.of<DeviceDataProvider>(context);

    Device slotDevice = slotProvider.getDevice(widget.slot);
    Device device = deviceProvider.getDevice(widget.slot);

    _dropdownMenuItems = buildDropdownMenuItems(deviceProvider.get());
    return ListTile(
      title: Row(
        children: <Widget>[
          SizedBox(
            width: 140,
            child: DropdownButton(
                isExpanded: true,
                disabledHint: Text(slotDevice.name),
                hint: Text(slotDevice.name),
                value: device,
                items: _dropdownMenuItems,
                onChanged: (value) {
                  device.setDevice(value);
                  slotDevice.setDevice(value);
                }),
          ),
          SizedBox(width: 10),
          SizedBox(width: 60, child: Text('SLOT#${slotDevice.slot}')),
        ],
      ),
      subtitle: Text(slotDevice.bdaddr, style: TextStyle(fontSize: 10.0)),
      leading: SizedBox(
        height: 40,
        width: 35,
        child: UsbBatteryImageAsset(slot: widget.slot),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
    );
  }
}

上面的代码中缺少什么。 SlotDataProvider 是“设备”的修复列表,具有名称、id 等属性。

@编辑 问题与组合框有关。如果我更改其他字段,它会起作用。

【问题讨论】:

    标签: flutter dart notifications widget provider


    【解决方案1】:

    通常我们使用流构建器根据更新的数据重建小部件 这将导致每次流发生变化时重新构建小部件 它接缝你的小部件是在第一次监听数据时构建一次的

    您是否尝试过将 gridview 包装在有状态的构建器中?

    【讨论】:

    • 这不是我们能做到的唯一方法。正如我上面提到的,它可以工作,但问题是组合框。
    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2021-12-24
    • 2020-03-03
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多