Compartilhar via


Usando a CLI do "winapp" com o Flutter

Este guia demonstra como usar a CLI do winapp com um aplicativo Flutter para adicionar a identidade do pacote e empacotar seu aplicativo como um MSIX.

A identidade do pacote é um conceito básico no modelo de Windows app. Ele permite que seu aplicativo acesse APIs específicas do Windows (como Notificações, Segurança, APIs de IA etc.), e tenha uma experiência de instalação/desinstalação limpa, entre outras funcionalidades.

Pré-requisitos

  1. SDK do Flutter: instale o Flutter seguindo o guia oficial.

  2. CLI do winapp: instale a winapp CLI utilizando o winget:

    winget install Microsoft.winappcli --source winget
    

1. Criar um novo aplicativo Flutter

Siga o guia nos documentos oficiais do Flutter para criar um novo aplicativo e executá-lo.

2. Atualizar código para verificar a identidade

Adicione o pacote ffi:

flutter pub add ffi

Substitua o conteúdo de lib/main.dart pelo seguinte código que verifica a identidade do pacote usando a API do Windows por meio de Dart FFI:

import 'dart:ffi';
import 'dart:io' show Platform;

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

String? getPackageFamilyName() {
  if (!Platform.isWindows) return null;

  final kernel32 = DynamicLibrary.open('kernel32.dll');
  final getCurrentPackageFamilyName = kernel32.lookupFunction<
      Int32 Function(Pointer<Uint32>, Pointer<Uint16>),
      int Function(
          Pointer<Uint32>, Pointer<Uint16>)>('GetCurrentPackageFamilyName');

  final length = calloc<Uint32>();
  try {
    final result =
        getCurrentPackageFamilyName(length, Pointer<Uint16>.fromAddress(0));
    if (result != 122) return null; // ERROR_INSUFFICIENT_BUFFER = 122

    final namePtr = calloc<Uint16>(length.value);
    try {
      final result2 = getCurrentPackageFamilyName(length, namePtr);
      if (result2 == 0) {
        return namePtr.cast<Utf16>().toDartString();
      }
      return null;
    } finally {
      calloc.free(namePtr);
    }
  } finally {
    calloc.free(length);
  }
}

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  late final String? _packageFamilyName;

  @override
  void initState() {
    super.initState();
    _packageFamilyName = getPackageFamilyName();
  }

  void _incrementCounter() {
    setState(() { _counter++; });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(16),
              margin: const EdgeInsets.only(bottom: 24),
              decoration: BoxDecoration(
                color: _packageFamilyName != null
                    ? Colors.green.shade50
                    : Colors.orange.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: _packageFamilyName != null
                      ? Colors.green
                      : Colors.orange,
                ),
              ),
              child: Text(
                _packageFamilyName != null
                    ? 'Package Family Name:\n$_packageFamilyName'
                    : 'Not packaged',
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            const Text('You have pushed the button this many times:'),
            Text('$_counter',
                style: Theme.of(context).textTheme.headlineMedium),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

3. Executar sem identificação

Crie e execute o aplicativo:

flutter build windows
.\build\windows\x64\runner\Release\flutter_app.exe

Você deve ver o aplicativo com um indicador laranja "Não empacotado".

4. Inicie o projeto com a CLI do winapp

winapp init

Quando solicitado:

  • Nome do pacote: Pressione Enter para aceitar o padrão
  • Nome do publicador: pressione Enter para aceitar o valor padrão ou insira seu nome
  • Versão: Pressione Enter para aceitar 1.0.0.0
  • Ponto de entrada: pressione Enter para aceitar o padrão (flutter_app.exe)
  • Setup SDKs: selecione "SDKs estáveis" para baixar Windows App SDK e gerar cabeçalhos C++

5. Depurar com identidade

  1. Compile o aplicativo:

    flutter build windows
    
  2. Aplicar identidade de depuração:

    winapp create-debug-identity .\build\windows\x64\runner\Release\flutter_app.exe
    
  3. Execute o executável:

    .\build\windows\x64\runner\Release\flutter_app.exe
    

Você deve ver o aplicativo com um indicador verde mostrando o Package Family Name.

Observação

Depois de executar flutter clean ou recompilar, você precisará executar novamente create-debug-identity , pois o executável é substituído.

6. Empacotar com MSIX

  1. Compilar para lançamento:

    flutter build windows
    
  2. Preparar o diretório do pacote:

    mkdir dist
    copy .\build\windows\x64\runner\Release\* .\dist\ -Recurse
    
  3. Gerar um certificado de desenvolvimento:

    winapp cert generate --if-exists skip
    
  4. Empacotar e assinar:

    winapp pack .\dist --cert .\devcert.pfx
    
  5. Instalar o certificado (executar como administrador):

    winapp cert install .\devcert.pfx
    
  6. Instale o pacote:

    Add-AppxPackage .\flutter-app.msix
    

Dica

  • A Microsoft Store assina o MSIX para você, não é necessário assinar antes do envio.
  • Azure Trusted Signing é uma ótima maneira de gerenciar certificados com segurança para pipelines de CI/CD.