You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

低版本Flutter项目集成人脸识别自动捕获库的方案求助

旧版Flutter项目集成人脸识别模块的问题及解决方案需求

我是Flutter新手,当前需为一个无法升级的旧版Flutter项目添加人脸识别自动捕获功能,但直接集成所需库行不通。我尝试创建新版Flutter模块集成该库,通过旧项目原生代码调用以获取返回的图片文件,却无法显示模块界面或获取文件。现寻求Android和iOS端的正确实现方法或替代方案,相关代码如下:

代码文件

1. AndroidManifest.xml

package="com.example.test_project">
   <application
        android:label="test_project"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
           android:name="io.flutter.embedding.android.FlutterActivity"
           android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
           android:hardwareAccelerated="true"
           android:windowSoftInputMode="adjustResize" />

       <!-- Don't delete the meta-data below.
            This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

2. build.gradle(项目级)

ext.kotlin_version = '1.7.10'
   repositories {
       google()
       mavenCentral()
   }

   dependencies {
       classpath 'com.android.tools.build:gradle:4.1.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')
}

tasks.register("clean", Delete) {
   delete rootProject.buildDir
}

3. build.gradle(app级)

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 34  

   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }

   kotlinOptions {
       jvmTarget = '1.8'
   }

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

   defaultConfig {
       // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
       applicationId "com.example.test_project"
       minSdkVersion 25
       targetSdkVersion 34
       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
       }
       profile {
           initWith debug
       }
   }
}

flutter {
   source '../..'
}

String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"
repositories {
   maven {
       url '/Users/phannhattan/Work/KAS/face_camera_module/build/host/outputs/repo'
   }
   maven {
       url "$storageUrl/download.flutter.io"
   }
}

dependencies {

   implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
   implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.0"))
   debugImplementation 'com.kas.face_camera_module:flutter_debug:1.0'
   profileImplementation 'com.kas.face_camera_module:flutter_profile:1.0'
   releaseImplementation 'com.kas.face_camera_module:flutter_release:1.0'
}

4. MainActivity.kt

package com.example.test_project

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "com.example.channel";
    private lateinit var channel: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL);

        channel.setMethodCallHandler {call, result ->
            if(call.method == "openFlutterModule") {
                result.success("abc")
                startActivity(
                    FlutterActivity
                        .withNewEngine()
                        .initialRoute("/face_camera")
                        .build(this)
                )
            }
        }
    }
}

5. main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  static const platform = MethodChannel('com.example.channel');

  Future<void> navigateToModule() async {
    try {
      // 向Kotlin发送指令
      String test = await platform.invokeMethod('openFlutterModule');
    } catch (e) {
      print("Failed to invoke method: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '',
              style: Theme.of(context).textTheme.displayLarge,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: navigateToModule,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

6. pubspec.yaml

name: test_projectdescription: A new Flutter project.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment: sdk: ">=2.16.2 <3.0.0"

dependencies: flutter: sdk: flutter

cupertino_icons: ^1.0.2

dev_dependencies: flutter_test: sdk: flutter

flutter_lints: ^1.0.0

flutter: uses-material-design: true

内容的提问来源于stack exchange,提问作者PNT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:29:50