我想从我的 Flutter 桌面应用程序中获取 Windows 用户的个人资料名称。有办法获取吗?
最佳答案
win32 方法是 GetUserName
。我们可以直接使用 ffi 调用它,而不是经历使用方法 channel 设置插件的麻烦。您需要 ffi和 win32包。
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
// This is the max win32 username length. It is missing from the win32 package,
// so we'll just create our own constant.
const unLen = 256;
String getUsername() {
return using<String>((arena) {
final buffer = arena.allocate<Utf16>(sizeOf<Uint16>() * (unLen + 1));
final bufferSize = arena.allocate<Uint32>(sizeOf<Uint32>());
bufferSize.value = unLen + 1;
final result = GetUserName(buffer, bufferSize);
if (result == 0) {
GetLastError();
throw Exception(
'Failed to get win32 username: error 0x${result.toRadixString(16)}');
}
return buffer.toDartString();
});
}
关于Flutter Desktop,如何获取Windows用户配置文件名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73979743/