플러터

1

warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings
warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
3 warnings
warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings

 

AOS로 실행은 되지만 위와 같은 빨간줄이 계속 뜨는걸 볼 수 있습니다.

이 경우에는 android/build.gradle에서 allprojects 내에 아래 코드를 추가해주시면 됩니다.

 

tasks.withType(JavaCompile) {
  options.compilerArgs << '-Xlint:-options'
}

'플러터 > Flutter 에러' 카테고리의 다른 글

[Flutter] Firebase iOS 실행 오류  (0) 2025.01.29

dependencies에 firebase 추가 후 iOS로 run 했을 때 아래와 같은 에러 발생할 경우

Lexical or Preprocessor Issue (Xcode): Include of non-modular header inside framework module
'firebase_database.FLTFirebaseDatabaseObserveStreamHandler':
'/Users/heitor.candido/Documents/inteliApp/inteli/ios/Pods/Headers/Public/Firebase/Firebase.h'
/Users/heitor.candido/.pub-cache/hosted/pub.dev/firebase_database-11.1.1/ios/Classes/FLTFirebaseDatabaseObserveStreamHandler.h:3:8

 

ios - Runner.xcworkspace를 Finder에서 열어서 더블클릭으로 실행.

 

Runner 클릭해서 Build Settings에서

"Allow Non-modular Includes in Framework Modules" 검색해서 Yes로 변경해주면 에러없이 실행됩니다.



 

analysis_options.yaml - rules 내에 3줄 작성 후 다시 실행.

prefer_const_constructors: false
prefer_const_literals_to_create_immutables: false
prefer_const_constructors_in_immutables: false

 


'플러터 > Flutter' 카테고리의 다른 글

[Flutter] MQTT 브로커에 연결해서 데이터 송수신  (0) 2024.03.21

- Flutter에서 MQTT를 이용한 발행(publish) & 구독(subscribe)

 

 

pubspec.yaml 추가

mqtt_client: ^9.6.2

mqtt_client 패키지 추가

 

 

코드 추가

  • MQTT 브로커 설정
Future<void> setupMqtt() async {
    // MQTT 브로커 연결
    client = MqttServerClient.withPort(broker, 'flutter_client', port);
    // MQTT 로그 출력
    client!.logging(on: false);

    // 리스너 등록
    client!.onConnected = onMqttConnected;
    client!.onDisconnected = onMqttDisconnected;
    client!.onSubscribed = onSubscribed;

    try {
      //
      await client!.connect();
    } catch (e) {
      print('Connected Failed.. \nException: $e');
    }
  }

 

 

  • MQTT publish
void publishData(String data) {
    final payload = jsonEncode(data);
    final builder = MqttClientPayloadBuilder();
    builder.addString(payload);

    client!.publishMessage(topic, MqttQos.exactlyOnce, builder.payload!);
  }

 

  • MQTT subscribe
// MQTT 연결 시 토픽 구독.
      client!.subscribe(topic, MqttQos.atLeastOnce);

      // 토픽 수신 리스너
      client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
        final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
        final String message =
        MqttPublishPayload.bytesToStringAsString(recMess.payload.message);

        // 수신한 메시지 처리
        setState(() {
          print(':: Received message: $message');
        });
      });

 

 

  • 전체코드
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String broker = /*브로커 주소*/;     // MQTT broker address
  final int port = /*포트*/;                 // MQTT broker port
  final String topic = /*토픽명*/;           // MQTT topic

  MqttServerClient? client;
  bool connected = false;

  @override
  void initState() {
    super.initState();
    setupMqtt();  // MQTT Set
  }

  Future<void> setupMqtt() async {
    // MQTT 브로커 연결
    client = MqttServerClient.withPort(broker, 'flutter_client', port);
    // MQTT 로그 출력
    client!.logging(on: false);

    // 리스너 등록
    client!.onConnected = onMqttConnected;
    client!.onDisconnected = onMqttDisconnected;
    client!.onSubscribed = onSubscribed;

    try {
      //
      await client!.connect();
    } catch (e) {
      print('Connected Failed.. \nException: $e');
    }
  }

  void onMqttConnected() {
    print(':: MqttConnected');
    setState(() {
      connected = true;
      // MQTT 연결 시 토픽 구독.
      client!.subscribe(topic, MqttQos.atLeastOnce);

      // 토픽 수신 리스너
      client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
        final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
        final String message =
        MqttPublishPayload.bytesToStringAsString(recMess.payload.message);

        // 수신한 메시지 처리
        setState(() {
          print(':: Received message: $message');
        });
      });
    });
  }

  void onMqttDisconnected() {
    print(':: MqttDisconnected');
    setState(() {
      connected = false;
    });
  }

  void onSubscribed(String topic) {
    print(':: Subscribed topic: $topic');
  }

  // 데이터 전송
  void publishData(String data) {
    final payload = jsonEncode(data);
    final builder = MqttClientPayloadBuilder();
    builder.addString(payload);

    client!.publishMessage(topic, MqttQos.exactlyOnce, builder.payload!);
    print(':: Send message: $data');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            connected
                ? Text('CONNECTED')
                : Text('DISCONNECTED'),
            SizedBox(height: 16,),
            ElevatedButton(
                onPressed: () async {
                  publishData('MQTT SEND DATA');
                },
                child: Text('BUTTON'),
            )
          ],
        ),
      ),
    );
  }
}

 

 


  • 앱 실행 시 'topic' 구독 확인

  • 버튼클릭 시 데이터 전송 (발행,구독을 모두 해둔 상태라 같이 보임)

  • MQTT Explorer로 데이터 확인

  • MQTT Explorer에서 데이터 publish 결과

 


'플러터 > Flutter' 카테고리의 다른 글

[Flutter]const 노란줄 안보이게 하기  (0) 2025.01.29

+ Recent posts