首页 > 解决方案 > 参数类型'Future' 不能分配给参数类型 'bool'。当我尝试从 Firestore 中检索布尔值时

问题描述

value: await statusonoff(device),我收到一条错误消息,提示无法将参数类型“Future”分配给参数类型“bool”。当我从 Firestore 中检索一个布尔值时


  static Future<bool>statusonoff(Device device) async {
    DocumentSnapshot variable = await Firestore.instance
        .collection('device-configs')
        .document(device.id)
        .get();
    return variable.data['value']['on'];
  }

CustomSwitch(
                    activeColor: Colors.green,
                    value: await statusonoff(device),
                    onChanged: (value) async {
                      DocumentSnapshot variable = await Firestore.instance
                          .collection('device-configs')
                          .document(device.id)
                          .get();
                      print(variable.data['value']['on']);
                      setState(() {
                        if (variable.data['value']['on'] == false) {
                          value = true;
                          _configMode = "on";
                          _updateDeviceConfig(context, device);
                        } else if (variable.data['value']['on'] == true) {
                          value = false;
                          _configMode = "off";
                          _updateDeviceConfig(context, device);
                        }
                        status = value;
                      });
                    },
                  ),

标签: flutterdartgoogle-cloud-firestore

解决方案


如果要使用boolean从 Future 中检索到的,则需要使用 FutureBuilder。

return FutureBuilder<bool>(
//! remove the parameters from statusonoff (Device device)
// or you could make it future:statusonoff(device)
//istantiate this instance of Device before you call it
  future:statusonoff,
  builder: (context, variable){
      if(variable.id.isNotEmpty)
       return CustomSwitch(
      //*put the rest of your code here  
      );
    }
);

推荐阅读