Home > Software design >  Flutter Desktop, how to get windows user profile name?
Flutter Desktop, how to get windows user profile name?

Time:10-08

I want to get windows user's profile name from my Flutter desktop app. Is there a way to get it?

CodePudding user response:

The win32 method for this is GetUserName. Rather than go through the trouble of setting up a plugin with a method channel, we can call this directly with ffi. You'll need the ffi and win32 packages.

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();
  });
}
  • Related