我从MQTT代理返回FETCH数据,并在变量中设置数据.我得到了这个问题,我可以知道为什么吗?

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: true,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: sensor01(),
    );
  }
}

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

  @override
  State<sensor01> createState() => _sensor01();
}

class _sensor01 extends State<sensor01> {
// connection succeeded
  void onConnected() {
    print('Connected');
  }

// unconnected
  void onDisconnected() {
    print('Disconnected');
  }

// subscribe to topic succeeded
  void onSubscribed(String topic) {
    print('Subscribed topic: $topic');
  }

// subscribe to topic failed
  void onSubscribeFail(String topic) {
    print('Failed to subscribe $topic');
  }

// unsubscribe succeeded
  void onUnsubscribed(String topic) {
    print('Unsubscribed topic: $topic');
  }

// PING response received
  void pong() {
    print('Ping response client callback invoked');
  }

  var data;

  Future<MqttServerClient> connect() async {
    MqttServerClient client = MqttServerClient.withPort(host, id, port);
    client.logging(on: false);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    // client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;
    client.autoReconnect = false;

    final connMessage = MqttConnectMessage()
        .authenticateAs(username, password)
        .withClientIdentifier(id)
        .startClean()
        // .withWillRetain()
        .withWillQos(MqttQos.atLeastOnce);
    client.connectionMessage = connMessage;

    try {
      await client.connect();
      // client.unsubscribe('topic/');

      client.subscribe(topic1, MqttQos.atLeastOnce);
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }

    client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload as MqttPublishMessage;
      final payload =
          MqttPublishPayload.bytesToStringAsString(message.payload.message);
      print('Received message:$payload from topic: ${c[0].topic}>');
      Map<String, dynamic> userMap = jsonDecode(payload);
      var user = dataList.fromJson(userMap);

      setState(() {
        if (user.sensorid == 'sensor01') {
          data = user.sensorid;
        }
      });
    });

    @override
    void initState() {
      super.initState();
      connect();
    }

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          appBar: AppBar(
            title: Text("MQTT"),
          ),
          body: FutureBuilder(
            future: connect(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasError) {
                return Center(
                  child: Text("Error: ${snapshot.error}"),
                );
              }

              // if succeed to connect
              if (snapshot.connectionState == ConnectionState.done) {
                return ListView(
                  children: [
                    Card(
                        child: ListTile(
                      title: Text(data),
                    ))
                  ],
                  padding: EdgeInsets.all(10),
                );
              }
              return Center(child: CircularProgressIndicator());
            },
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

我有一个错误.该错误显示在覆盖小部件上方的Fure函数中.我应该添加什么才能使代码即使返回的数据为空也能运行?

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<MqttServerClient>', is a potentially non-nullable type.

如何解决这个错误??

推荐答案

在函数connect()中,您的返回类型为MqttServerClient:

Future<MqttServerClient> connect() async {}

但你什么都没拿到. 您的函数不返回任何内容--它是void.

所以,改变吧:

Future<MqttServerClient> connect() async {}

致:

Future<void> connect() async {}

Flutter相关问答推荐

SingleChildScrollView正在将Container的高度限制为子对象,尽管使用了Expanded Inside Row()

在Flutter 中压缩图片返回空

为什么PUT方法没有发出任何响应?

BoxConstraints强制使用无限宽度(列中的Listview)

Flutter /dart 列表.第一个子类列表中的Where()错误

如何在flutter中使用youtube_explod_start加载下一页

运行调试flutter应用程序时出错:B/BL超出范围(最大+/-128MB)到'';

如何将取消图标放置在右上角

Flutter ImagePicker - 在 onPressed 中异步获取图像显示 lint 警告

Flutter 判断 Uint8List 是否有效 Image

我想在文本结束后显示分隔线.它会在第一行、第二行或第三行结束

如何制作flutter showDialog、AlertDialog屏障 colored颜色 渐变

如何为文本主题设置多种 colored颜色 ?

type '({bool growable}) => List' 不是类型转换中类型 'List' 的子类型

Flutter 中出现错误空判断运算符用于空值

Firebase 中的查询限制 - .orderBy() 错误

在 Flutter 中更改高架按钮 OnPressed 的背景 colored颜色

Flutter Web Responsiveness 效率不高

如何使用 Riverpod 在运行时动态创建提供程序?

如何从 MemoryFileSystem 字节创建假 dart:io 文件?