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

View File

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

View File

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