Home > Enterprise >  How to use WebM file in Flutter?
How to use WebM file in Flutter?

Time:12-19

Because GIF file is really heavy, I want to use WebM file instead of Gif file. However, VS Code can't read WebM file and the Flutter also can't read the file.

Therefore, if I run the Flutter project, it shows the error that Exception: Invalid image data. How can I fix this problem and what's the best way to use WebM file instead of GIF file?

This is the code that I used:

child: Image.asset(
  // (note.getCategoryName() == Constants.TAG_CATEGORY_NAME_DIET)
  //     ? 'assets/ani_give_coffee_diet.gif'
  //     : (note.getCategoryName() == Constants.TAG_CATEGORY_NAME_EXERCISE)
  //         ? 'assets/ani_give_coffee_exercise.gif'
  //         : 'assets/ani_give_coffee_diet.gif',
  (note.getCategoryName() ==
          Constants
              .TAG_CATEGORY_NAME_EXERCISE)
      ? 'assets/ani_give_coffee_exercise.webm'
      : 'assets/ani_give_coffee_diet.webm',
),

CodePudding user response:

First, install the video_player package.

Then, try the following code:

VideoPlayerController _controller;

@override
void initState() {
  _controller = VideoPlayerController.asset(note.getCategoryName() == Constants.TAG_CATEGORY_NAME_EXERCISE) ? 'assets/ani_give_coffee_exercise.webm' : 'assets/ani_give_coffee_diet.webm')
  ..initialize().then((_) {
    setState(() {});
  });

  _controller.setLooping(true);

  super.initState();
}

@override
void dispose() {
  _controller.dispose();

  super.dispose();
}

_controller.value.isInitialized
  ? AspectRatio(
      aspectRatio: _controller.value.aspectRatio,
      child: VideoPlayer(_controller),
    )
  : Container(),

CodePudding user response:

If not necessary, instead of using WebM or gif, try using WebP image format that is smaller in size and now supported by iOS and Android. The method is same as other image formats.

child: Image.asset(
  (note.getCategoryName() ==
          Constants
              .TAG_CATEGORY_NAME_EXERCISE)
      ? 'assets/ani_give_coffee_exercise.webp'
      : 'assets/ani_give_coffee_diet.webp',
),
  • Related