Search code examples
flutterdartflutter-layout

Flutter / how can i set border to container like samsung one ui app icon


I want to set the border of the container, something similar to the photo below

enter image description here


Solution

  • You need to find png of that icon and give it's path to mask parameter and give your Image widget to image parameter.

    import 'dart:ui' as ui;
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    class MaskedImage extends StatelessWidget {
      final Widget image;
      final String mask;
      final BoxFit fit;
    
      const MaskedImage({
        Key? key,
        required this.image,
        required this.mask,
        this.fit = BoxFit.cover,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return LayoutBuilder(
          builder: (context, constraints) {
            return FutureBuilder<List>(
              future: _createShaderAndImage(
                image,
                mask,
                constraints.maxWidth,
                constraints.maxHeight,
              ),
              builder: (context, snapshot) {
                if (!snapshot.hasData) return const SizedBox.shrink();
                return ShaderMask(
                  blendMode: BlendMode.dstATop,
                  shaderCallback: (rect) => snapshot.data![0],
                  child: snapshot.data![1],
                );
              },
            );
          },
        );
      }
    
      Future<List> _createShaderAndImage(
        Widget image,
        String mask,
        double w,
        double h,
      ) async {
        ByteData maskData = await rootBundle.load(mask);
    
        ui.Codec codec = await ui.instantiateImageCodec(
          maskData.buffer.asUint8List(),
          targetWidth: w.toInt(),
          targetHeight: h.toInt(),
          allowUpscaling: false,
        );
        ui.FrameInfo fi = await codec.getNextFrame();
    
        ImageShader shader = ImageShader(
          fi.image,
          TileMode.clamp,
          TileMode.clamp,
          Matrix4.identity().storage,
          filterQuality: ui.FilterQuality.high,
        );
        return [shader, image];
      }
    }