How to Convert List<int> to Unit8List in Flutter/Dart

This example shows you how to convert List<int> to Unit8List in Dart or Flutter. It would help if you had this function while working with image processing such as resizing, compressing, or editing images in Flutter. See the example below:

import 'dart:typed_data';
Uint8List byte = Uint8List Uint8List.fromList(List<int> elements);

For Example:

This function is used in this example: How to Resize Image Size in Flutter

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as IMG;

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  Uint8List? wdata;
  Uint8List? bytes;
  
  @override
  void initState() {
    Future.delayed(Duration.zero, () async {
        String imgurl = "https://www.fluttercampus.com/img/banner.png";
        bytes = (await NetworkAssetBundle(Uri.parse(imgurl)).load(imgurl)).buffer.asUint8List();
        
        IMG.Image? img = IMG.decodeImage(bytes!);
        IMG.drawString(
          img!, //image Unit8List bytes
          IMG.arial_48, //font and size
          100, 100,  //x and y offset of cursor
          "THIS IS FLUTTERCAMPUS", //text to write
          color: 0xff00ff00 //0xff is transparancy, and 00ff00 is color code
        );
        wdata = Uint8List.fromList(IMG.encodePng(img));
        //convert List<int> to Unit8List
        setState(() {});
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar( 
              title: Text("Resize Image"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            padding: EdgeInsets.all(30),
            child: Column(
              children:[
                Text("Original Image"),
                bytes != null?Image.memory(bytes!, width:200):Container(),

                Text("Image with Text"),
                wdata != null?Image.memory(wdata!,  width:200):Container(),
                
              ]
            )
          ),
           
       );
  }
}

In this example, we have converted List<int> to Unit8List while resizing the image size in Flutter. This is the way, you can convert List<int> to Unit8List.

No any Comments on this Article


Please Wait...