/Users/glory/Desktop/mac/flutter_glory/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Text(
          'Hello World',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20.0,
          ),
        ),
      ),
    ),
  ));

  // BLE 모듈 연결 함수 호출
  connectToBLEModule();
}

// BLE 모듈의 MAC 주소
const String DEVICE_MAC_ADDRESS = "00:11:22:33:44:55";

// BLE 모듈과 연결하는 함수
Future<void> connectToBLEModule() async {
  // FlutterBlue 객체 생성
  FlutterBlue flutterBlue = FlutterBlue.instance;

  // BLE 모듈 스캔 시작
  flutterBlue.startScan(timeout: Duration(seconds: 4));

  // BLE 모듈 스캔 결과 확인
  flutterBlue.scanResults.listen((results) {
    for (ScanResult r in results) {
      // BLE 모듈을 찾으면 연결 시도
      if (r.device.id.toString() == DEVICE_MAC_ADDRESS) {
        // 연결 시도
        r.device.connect();

        // 연결 완료까지 대기
        r.device.state.listen((event) async {
          if (event == BluetoothDeviceState.connected) {
            // 연결된 BLE 모듈 서비스 찾기
            List<BluetoothService> services = (await r.device.discoverServices()).toList();

            // 연결된 BLE 모듈 서비스 확인
            for (BluetoothService service in services) {
              print("Service UUID: ${service.uuid}");

              // 서비스의 특성(Characteristic) 확인
              List<BluetoothCharacteristic> characteristics =
              await service.characteristics.toList();

              for (BluetoothCharacteristic c in characteristics) {
                print("Characteristic UUID: ${c.uuid}");

                // 특성(Characteristic)에서 데이터 수신
                c.value.listen((value) {
                  print("Received data: ${String.fromCharCodes(value)}");
                });
              }
            }
          }
        });
      }
    }
  });
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig { //230318_2243 : 새로 작성한 부분
        // TODO: Specify your own unique Application ID (<https://developer.android.com/studio/build/application-id.html>).
        applicationId "com.example.hello_world"
        // You can update the following values to match your application needs.
        // For more information, see: <https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration>.
        minSdkVersion 19 // 수정된 부분
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    /*defaultConfig { //230318_2243 : 원래 있던 부분
        // TODO: Specify your own unique Application ID (<https://developer.android.com/studio/build/application-id.html>).
        applicationId "com.example.hello_world"
        // You can update the following values to match your application needs.
        // For more information, see: <https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration>.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }*/

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
name: hello_world
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at <https://developer.android.com/studio/publish/versioning>
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# <https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html>
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.19.1 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter
  flutter_blue: ^0.8.0 #230318_2242 플러터 ble 모듈

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: <https://dart.dev/tools/pub/pubspec>

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # <https://flutter.dev/assets-and-images/#resolution-aware>

  # For details regarding adding assets from package dependencies, see
  # <https://flutter.dev/assets-and-images/#from-packages>

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see <https://flutter.dev/custom-fonts/#from-packages>


[data:image/svg+xml,%3csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20version=%271.1%27%20width=%2730%27%20height=%2730%27/%3e](data:image/svg+xml,%3csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20version=%271.1%27%20width=%2730%27%20height=%2730%27/%3e)

오류 내용

Launching lib/main.dart on SM G998N in debug mode...
Running Gradle task 'assembleDebug'...
/Users/glory/Desktop/mac/flutter_glory/android/app/src/debug/AndroidManifest.xml Error:
	uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:flutter_blue] /Users/glory/Desktop/mac/flutter_glory/build/flutter_blue/intermediates/merged_manifest/debug/AndroidManifest.xml as the library might be using APIs not available in 16
	Suggestion: use a compatible library with a minSdk of at most 16,
		or increase this project's minSdk version to at least 19,
		or use tools:overrideLibrary="com.pauldemarco.flutter_blue" to force usage (may lead to runtime failures)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugMainManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:flutter_blue] /Users/glory/Desktop/mac/flutter_glory/build/flutter_blue/intermediates/merged_manifest/debug/AndroidManifest.xml as the library might be using APIs not available in 16
  	Suggestion: use a compatible library with a minSdk of at most 16,
  		or increase this project's minSdk version to at least 19,
  		or use tools:overrideLibrary="com.pauldemarco.flutter_blue" to force usage (may lead to runtime failures)

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at <https://help.gradle.org>

BUILD FAILED in 1m 56s

┌─ Flutter Fix ─────────────────────────────────────────────────────────────────────────────────┐
│ The plugin flutter_blue requires a higher Android SDK version.                                │
│ Fix this issue by adding the following to the file                                            │
│ /Users/glory/Desktop/mac/flutter_glory/android/app/build.gradle:                              │
│ android {                                                                                     │
│   defaultConfig {                                                                             │
│     minSdkVersion 19                                                                          │
│   }                                                                                           │
│ }                                                                                             │
│                                                                                               │
│ Note that your app won't be available to users running Android SDKs below 19.                 │
│ Alternatively, try to find a version of this plugin that supports these lower versions of the │
│ Android SDK.                                                                                  │
│ For more information, see:                                                                    │
│ <https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration>          │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
  1. Flutter Blue 라이브러리의 호환 가능한 버전을 사용합니다. 이 경우에는 minSdkVersion을 16으로 유지할 수 있습니다.
  2. 프로젝트의 minSdkVersion을 19 이상으로 올립니다.
  3. Flutter Blue 라이브러리를 사용하는 곳에서 tools:overrideLibrary="com.pauldemarco.flutter_blue" 속성을 추가합니다. 이 방법은 런타임 오류가 발생할 가능성이 있으므로 주의해야 합니다.
  4. 해당 오류를 해결하기 위해서는, 에러 메시지에 나와있는 대로 /Users/glory/Desktop/mac/flutter_glory/android/app/build.gradle 파일을 열고, 다음과 같이 defaultConfig 블록에 minSdkVersion 값을 19로 변경하면 됩니다.
markdownCopy code
android {
    ...
    defaultConfig {
        ...
        minSdkVersion 19
        ...
    }
}