Flutter

Use TwicPics Flutter Widget to get images and videos integration best practices out-of-the-box.

TwicPics Flutter Widget is available as a Flutter Package.

Installation

Add the twicpics_components package to your Flutter project by running:

flutter pub add twicpics_components

Setup

Install TwicPics in your Flutter project

You will need a TwicPics domain to initialize the package. Create an account for free to get your domain.
// main.dart

import 'package:twicpics_components/twicpics_components.dart';

void main() {
  install(
    domain: "https://<your-domain>.twic.pics/",
  );
  runApp(...);
}

For an exhaustive list of options, see Setup Options.

Setup Options

OptionDescriptionTypeDefault
cacheCleanOnStartUpClears the cache when the application starts.booleanfalse
cacheStalePeriodDefines the duration of validity of a cached asset.DurationDuration( days: 7)
cacheMaxNrOfObjectsDefines how large the cache is allowed to be.Integer200
debugActivate logs from the cache manager.booleanfalse
domainThis is your very own TwicPics domain. Providing it is mandatory.String
maxDPRTwicPics will take the "Device Pixel Ratio" (DPR) of the current device into consideration when determining the sizes of images to load. By default, it will not take a DPR greater than 2 into consideration. If the DPR of the device is higher than 2, TwicPics will assume it to be 2. Using maxDPR, you can lower this limit down to 1 or be more permissive (for instance by setting it to 3 or 4).Number2
pathPath to prepend to all src attributes. For instance, if path is "some/folder" then a src attribute set to "image.jpg" will be expanded into "some/folder/image.jpg"String
stepTo avoid requesting too may variants of the same image, TwicPics will round the width of images to the closest multiple of step. The height will then be computed in order to respect the original aspect ratio.Integer50

Usage

TwicImg and TwicVideo come as Flutter Widgets and are used as such.

Basic usage

// my_widget.dart

import 'package:twicpics_components/twicpics_components.dart';

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
    );
  }
}

Bulk loading

When embedding TwicImg or TwicVideo in a lazily loading-compatible tree, it is recommended to disable lazy-loading feature:

// grid_sample.dart

class GridSample extends StatelessWidget {
  const GridSample({super.key});
  
  Widget build(BuildContext context) {
    return GridView.count(
      primary: false,
      crossAxisCount: 3,
      children: [
        TwicImg(
          src: 'path/to/my/image',
          eager: true,
        ),
        TwicVideo(
          src: 'path/to/my/video',
          eager: true,
        ),
        // ...
      ]
    );
}

Choose your focus

You can control the crop function by using the focus property.

Read more about focus.

Set the focus point to coordinates

// my_widget.dart

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
      focus: '30px40p', // this will set the focus point coordinates using relative lengths
    );
  }
}
// my_widget.dart

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
      focus: '345x678', // this will set the focus point coordinates using absolute lengths
    );
  }
}

Set the focus automagically

// my_widget.dart

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
      focus: 'auto', // the focus point will be chosen automagically for you
    );
  }
}
Note that auto is not implemented for videos yet and is only available for TwicImg.

Working with ratio="none"

Allows to display both image or video with a free height while respecting its natural aspect-ratio.

Hero image

An image that occupies all available space:

// my_widget.dart

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

class HeroSample extends StatelessWidget {
  const HeroSample({super.key});
  
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: TwicImg(
        src: 'path/to/my/image.jpg',
          ratio: 'none',
        ),
    );
  }
}

Hero video

An video that occupies all available space:

// my_widget.dart

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

class HeroSample extends StatelessWidget {
  const HeroSample({super.key});
  
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: TwicVideo(
        src: 'path/to/my/video.jpg',
          ratio: 'none',
        ),
    );
  }
}

Hero banner

You can specify the height of your image (or video) while respecting its natural aspect-ratio and optimizing your Cumulative Layout Shift (CLS) metric.

// my_widget.dart

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

class HeroBanner extends StatelessWidget {
  const HeroBanner({super.key});
  
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 200,
      child: TwicImg(
        src: 'path/to/my/image.jpg',
        ratio: 'none',
      ),
    );
  }
}

Reframe your image

You can reframe your image on the main subject(s) it contains.

In cover mode, the resulting image will respect ratio while maximizing the area occupied by the main subject(s).

In contain mode, the image will be cropped as close as possible to the main subject(s).

To activate automatic cropping, simply add the refit property to your widget call.

Read more about refit.

// my_widget.dart

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      anchor: TwicPosition.right, // will align main subject(s) with the right border
      src: 'path/to/my/image',
      mode: TwicMode.cover, // will maximize the area occupied by the main subject(s) in a squared area
      refit: '10p', // will add a 10% padding around the main subject(s)
    );
  }
}
// my_widget.dart

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
      mode: TwicMode.contain, // will crop the image as close as possible to main subject(s)
      refit: true, // default refit without any padding
    );
  }
}
Note that refit is not implemented for videos yet and is only available for TwicImg.

Working with Row Widget

When using Row Widget you have to constrain available width for TwicImg as in:

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

class RowSample extends StatelessWidget {
  const RowSample({super.key});
  
  Widget build(BuildContext context) {
    return Row(
      children: [
        SizedBox(
          width: 100, //fixed width
          child: TwicImg(
            src:'path/to/my/image',
          ),
        ),
        Expanded( // makes child fills the available space
          child: TwicVideo(
            src:'path/to/my/video',
          ),
        ),
      ],
    );
  }
}

Widget Properties

TwicImg

TwicImg( 
  { 
      Key? key,
      TwicPosition? anchor,
      bool? eager,
      String? focus,
      String? intrinsic,
      TwicMode? mode,
      TwicPlaceholder? placeholder,
      TwicPosition? position,
      String? preTransform,
      <String? | double?> ratio,
      <String? | bool?> refit,
      required String src,
      int? step,
      Duration? transitionDuration,
  } 
)
AttributeDescriptionTypeDefault
keyKeeps widget state when parent tree rebuilds.Key
anchorPositions the image in both TwicMode.contain and TwicMode.cover mode. position and focus take precedence in TwicMode.contain and TwicMode.cover mode respectively. Please note that anchor is applied after an eventual preTransform.TwicPosition
eagerLoad the image as soon as the widget is mounted. This effectively means disabling lazy loading for this image. Recommended when TwicImg is placed within a parent that natively handles lazy-loading.booleanfalse
focusSets the focus point in TwicMode.cover mode. focus takes precedence over anchor when both are provided. See the TwicPics focus attribute documentation for more information. Only use this attribute if you need a specific focus point or if you want to leverage smart cropping with focus="auto": if you only need border-based positionning (TwicPosition values), use anchor instead.String
intrinsicDimensions in pixels of the original image, formatted <width>x<height> (eg. 1920x1080). It prevents image upscaling and limits the number of generated variants. If using preTransform, you should specify the intrinsic dimensions of the resulting image. Using incorrect values can lead to display issues, see the intrinsic attribute documentation. String
modeDetermines if the image fills the area and is cropped accordingly (TwicMode.cover) or if the image will sit inside the area with no cropping (TwicMode.contain).TwicModeTwicMode.cover
placeholderDisplays a low quality version before the final image is actually loaded.TwicPlaceholderTwicPlaceholder.preview
positionPositions the image in TwicMode.contain mode. position takes precedence over anchor when both are provided. Only use this property if you need precise positionning: if you only need border-based positionning (TwicPosition values), use anchor instead.TwicPositionTwicPosition.center
preTransformA slash-separated list of TwicPics API transformations to be performed before resizing the image (see the TwicPics Manipulation documentation). Note that anchor and focus are applied after preTransform: if you need to specify a specific focus point for your preTransform then it needs to be part of the expression (like preTransform="focus=auto/crop=50px50p" for instance). Be aware that using this option can lead to unexpected results so use with caution!String
ratioA unitless width/height or width:height value pair (as in 4/3 or 4:3) that defines the aspect ratio of the display area. If height is not specified, it is assumed to be 1. A square area will be created by default. When set to none, ratio is determined based on width and height as computed by the Flutter following the parent size definitions. You are responsible for properly sizing the component when ratio="none".String or number1
refitReframes the image to maximize the area occupied by the main object(s) while respecting ratio in cover mode. Crops the image as close as possible to the main object(s) in contain mode. Can be true, false or a list of comma-separated length defining padding. See the TwicPics refit documentation for more information.boolean or Stringfalse
srcMandatory path to the image.String
stepSee the TwicPics step attribute documentation for more information.int
transitionDurationDuration of the transition effect between placeholder and the final image.DurationDuration( milliseconds: 400 )

TwicVideo

TwicVideo( 
  { 
      Key? key,
      TwicPosition? anchor,
      <String? | double?> duration,
      bool? eager,
      String? focus,
      <String? | double?> from,
      String? intrinsic,
      TwicMode? mode,
      <String? | double?> posterFrom,
      TwicPlaceholder? placeholder,
      TwicPosition? position,
      String? preTransform,
      <String? | double?> posterFrom,
      <String? | double?> ratio,
      required String src,
      <String? | double?> to,
      int? step,
      Duration? transitionDuration,
  } 
)
AttributeDescriptionTypeDefault
keyKeeps widget state when parent tree rebuilds.Key
anchorPositions the video in both TwicMode.contain and TwicMode.cover mode. position and focus take precedence in TwicMode.contain and TwicMode.cover mode respectively. Please note that anchor is applied after an eventual preTransform.TwicPosition
durationLimits the duration of the video. duration is expressed in seconds and must be a positive number. duration will not move the starting point of the video: to do so, you'll have to use the from property. See duration documentation.String or number
eagerLoad the video as soon as the widget is mounted. This effectively means disabling lazy loading for this video. Recommended when TwicVideo is placed within a parent that natively handles lazy-loading.booleanfalse
focusSets the focus point in TwicMode.cover mode. focus takes precedence over anchor when both are provided. See the TwicPics focus attribute documentation for more information. Only use this attribute if you need a specific focus point: if you only need border-based positionning (TwicPosition values), use anchor instead.String
fromMoves the starting point of the video. from is expressed in seconds and must be a positive number. from will not move the end point of the video: to do so, you'll have to use the duration or to properties. See from documentation. See from documentation.String or number
intrinsicDimensions in pixels of the original video, formatted <width>x<height> (eg. 1920x1080). It prevents video upscaling and limits the number of generated variants. If using preTransform, you should specify the intrinsic dimensions of the resulting video. Using incorrect values can lead to display issues, see the intrinsic attribute documentation. String
modeDetermines if the video fills the area and is cropped accordingly (TwicMode.cover) or if the video will sit inside the area with no cropping (TwicMode.contain).TwicModeTwicMode.cover
placeholderDisplays a low quality version before the final video is actually loaded.TwicPlaceholderTwicPlaceholder.preview
positionPositions the video in TwicMode.contain mode. position takes precedence over anchor when both are provided. Only use this property if you need precise positionning: if you only need border-based positionning (TwicPosition values), use anchor instead.TwicPositionTwicPosition.center
posterFromDetermines which frame of the source video should be used as a poster / preview. posterFrom is expressed in seconds and must be a positive number. By default posterFrom is equal to 0, meaning the very first frame of the video is used. posterFrom will not modify the video in any way: to do so, you'll have to use the duration, from or to properties.String or number
preTransformA slash-separated list of TwicPics API transformations to be performed before resizing the video (see the TwicPics Manipulation documentation). Note that anchor and focus are applied after preTransform: if you need to specify a specific focus point for your preTransform then it needs to be part of the expression (like preTransform="focus=20px30p/crop=50px50p" for instance). Be aware that using this option can lead to unexpected results so use with caution!String
ratioA unitless width/height or width:height value pair (as in 4/3 or 4:3) that defines the aspect ratio of the display area. If height is not specified, it is assumed to be 1. A square area will be created by default. When set to none, ratio is determined based on width and height as computed by the Flutter following the parent size definitions. You are responsible for properly sizing the component when ratio="none".String or number1
srcMandatory path to the video.String
stepSee the TwicPics step attribute documentation for more information.int
toMoves the end point of the video. to is expressed in seconds and must be a positive number. to will not move the starting point of the video: to do so, you'll have to use the from property. See to documentation.String or number
transitionDurationDuration of the transition effect between placeholder and the video or its poster.DurationDuration( milliseconds: 400 )

TwicMode enum

Defines how assets should be resized to fit its container.

ValueDescription
containresize asset so that it completely fits inside the target area while conserving the original aspect ratio.
coverresize asset so that it completely fills the target area while conserving the original aspect ratio.

TwicPosition enum

Defines a position within the parent container.

ValueDescription
bottomThe center point along the bottom edge.
bottomLeftThe bottom left corner.
bottomRightThe bottom right corner.
centerThe center point, both horizontally and vertically.
leftThe center point along the left edge.
rightThe center point along the right edge.
topThe center point along the top edge.
topLeftThe top left corner.
topRightThe top right corner.

TwicPlaceholder enum

Defines placeholder characteristics.

ValueDescription
previewdisplays a blurry preview of requested asset.
maincolorfills container with a solid color containing the most important color in the requested asset.
meancolorfills container with a solid color containing the mean color in the requested asset.
nonedisplays an empty container.

Feedback and support

TwicPics Flutter Widgets are open-source on GitHub. For features requests and bugs, open an issue. The TwicPics team also remains available for support via the live chat (at the bottom right.)

responsive images

The All-In-One Toolbox For Your Medias

The simplest, most powerful way to tackle responsive images & videos