Verified Solution[StackOverflow/docker] Best practice to build flutter docker image on mac non-x86 for use on x86-64 machine
Sponsored Content
### ROOT CAUSE
The issue arises because the user is attempting to build a Flutter Docker image on an ARM-based Mac (non-x86) to produce artifacts for an x86-64 machine. Flutter's default build process targets the host architecture, and cross-compilation for different architectures (like x86-64) isn't natively supported. The challenge involves ensuring the Docker image includes the necessary tools (like QEMU) for cross-compilation and properly configuring the build environment.
### CODE FIX
Use a multi-architecture Docker image and configure the build to target x86-64 via QEMU emulation. Here's the solution:
1. **Dockerfile**: Use a base image with ARM support and install QEMU for cross-compilation.
2. **Build Configuration**: Set environment variables to target x86-64 and use `buildx` for multi-arch builds.
```dockerfile
# Dockerfile
FROM --platform=linux/arm64v8 ubuntu:20.04
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
qemu-user-static \
git \
curl \
&& rm -rf /var/lib/apt-get/lists/*
# Install Flutter
RUN curl -o flutter.tar.gz https://storage.googleapis.com/flutter_infra_release/flutter/a48e0478ef/flutter_linux_3.10.10.tar.gz \
&& tar -xzvf flutter.tar.gz -C /opt \
&& mv /opt/flutter_linux_3.10.10 /opt/flutter \
&& export PATH="/opt/flutter/bin:$PATH"
# Configure QEMU for cross-compilation
COPY qemu-overlay/etc /etc
RUN ln -s /usr/bin/qemu-x86_64-static /usr/bin/qemu-x86_64-static
# Build for x86-64
CMD ["sh", "-c", "flutter build apk --target-platform=android-x64"]
```
**Steps to build:**
1. Install `docker buildx` plugin (if not enabled by default).
2. Build the image with platform targeting:
```bash
docker buildx build --platform linux/amd64 -t flutter-x86 --push .
```
**Explanation:**
- The `--platform` flag forces Docker to build for the specified architecture.
- `qemu-user-static` enables cross-compilation by translating system calls.
- Flutter's `--target-platform` flag directs the build to use the x86-64 architecture.
This approach ensures the Docker image runs on ARM but produces x86-64 artifacts by leveraging QEMU for emulation.
Deploy on DigitalOcean ($200 Credit)
Related Fixes
[StackOverflow/go] Go RPC streaming send not working properly when optional values not provided
[docker/cli] Wrong ANSI font representation
[docker/cli] Wrong ANSI font representation