【问题标题】:notifyListeners() Not Updating UL at the same TimenotifyListeners() 不同时更新 UL
【发布时间】:2020-09-08 06:55:36
【问题描述】:

我是 Flutter 的新开发人员,我使用 Flutter 使应用程序失明所以我正在使用 Provider 数据包,当蓝牙状态发生变化时我需要更改小部件 UL 我编写了执行此操作的代码,但在我的代码中小部件第二次运行应用程序后UL更改不会同时更改我可以同时更改小部件

类 ChangeNotifier

class Per extends ChangeNotifier {

  bool BLu;

  Per.initialize(){
    CheckBluetooth();
  }

 CheckBluetooth()async{
  await  FlutterBlue.instance.state.listen((state)async {
   if(state==BluetoothState.on){
     BLu=true;
     notifyListeners();
   }else{
     BLu=false;
     notifyListeners();
   }

    if (state==BluetoothState.off) {
      BLu=false;
      notifyListeners();
    } else if (state==BluetoothState.on){
        BLu=true;
      notifyListeners();

    }

  });

}

类小部件

   class _HomeState extends State<Hom> {
      @override
      Widget build(BuildContext context) {
        final modal =Provider.of<Per>(context);

      if(modal.BLu!=true){
        return Center(child: Text('NO'),);

      }else{
        return Center(child: Text('YES'),);
      }


    }

    }

多提供者

 return MultiProvider(providers: [
        ChangeNotifierProvider.value(value:AuthProvider.initialize()),
      ChangeNotifierProvider.value(value:Per.initialize()),
])

【问题讨论】:

  • 非常感谢,我在 chaking blu 后调用 CheckBluetooth() 解决了这个问题

标签: flutter provider flutter-change-notifier


【解决方案1】:

您实际上需要重新运行 CheckBluetooth() 函数。目前它只从Per.initialize() 运行一次。

您可以通过调用modal.CheckBluetooth(); 来完成此操作。然后它将执行该功能并在完成后通过 Provider 更新 UI。 Provider 不会继续运行其功能,以防万一发生变化,您必须手动执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2021-12-23
    • 2021-03-17
    • 2021-12-02
    • 1970-01-01
    • 2020-07-16
    • 2021-11-12
    相关资源
    最近更新 更多