This commit is contained in:
thinkerr24 2025-08-05 08:21:05 +08:00
parent 2b73e2ecb6
commit 81fa15021e
3 changed files with 19 additions and 25 deletions

View File

@ -5,21 +5,22 @@ import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val CHANNEL = "com.example/native_utils"
private val uuidGenerator = Generators.randomBasedGenerator()
private val CHANNEL = "com.example/uuid_generator"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"generateRandomUUID" -> {
try {
val uuid = uuidGenerator.generate()
result.success(uuid.toString())
} catch (e: Exception) {
result.error("UUID_ERROR", e.message, null)
}
"generateStandardUUID" -> {
result.success(Generators.randomBasedGenerator().generate().toString())
}
"generateShortUUID" -> {
val length = call.argument<Int>("length") ?: 8
val uuid = Generators.randomBasedGenerator()
.generate()
.toString()
.replace("-", "")
.substring(0, length.coerceIn(1, 32))
result.success(uuid)
}
else -> result.notImplemented()
}

View File

@ -115,7 +115,8 @@ class _MyHomePageState extends State<MyHomePage> {
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final uuid = await NativeUuidGenerator.generateRandomUUID();
int len = 7;
final uuid = await NativeUuidGenerator.generateShortUUID(length: len);
setState(() {
_counter = uuid;
});

View File

@ -2,22 +2,14 @@ import 'package:flutter/services.dart';
class NativeUuidGenerator {
static const MethodChannel _channel =
MethodChannel('com.example/native_utils');
MethodChannel('com.example/uuid_generator');
static Future<String> generateRandomUUID() async {
try {
return await _channel.invokeMethod('generateRandomUUID');
} on PlatformException catch (e) {
throw Exception("Failed to generate UUID: ${e.message}");
}
static Future<String> generateStandardUUID() async {
return await _channel.invokeMethod('generateStandardUUID');
}
static Future<String> generateTimeBasedUUID() async {
try {
return await _channel.invokeMethod('generateTimeBasedUUID');
} on PlatformException catch (e) {
throw Exception("Failed to generate UUID: ${e.message}");
}
static Future<String> generateShortUUID({int length = 8}) async {
return await _channel.invokeMethod('generateShortUUID', {'length': length});
}
}