Search code examples
imageflutterdartcolorscolor-palette

How to get dominant color from image in flutter?


I want to extract dominant color from a image so that i can apply it as blending to other images. how can i achieve that??

In my current code i have given color manually but i want it to be generated by app.

class MyApp extends StatelessWidget {

  Color face = new HexColor("a8a8a8");
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image from assets"),
        ),
        body: Column (
            mainAxisAlignment: MainAxisAlignment.center,
              children:<Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children:<Widget>[
                      new Image.asset('assets/images/6.jpg',
                        color: face, colorBlendMode:BlendMode.modulate ,
                        fit:BoxFit.cover,
                        height: 50,
                        width: 50,
                      ),


                new Image.asset('assets/images/1.jpg',
              color: face, colorBlendMode: BlendMode.modulate,
            fit:BoxFit.cover,
                  height: 200,
                  width: 200,
          ),
                    ]),
                ])),
    );
  }
}



Solution

  • I found solution using palette_generator package.. First import library

    import 'package:palette_generator/palette_generator.dart';
    

    add it in pubspec.yaml file too

    The below function will return palette

    Future<PaletteGenerator>_updatePaletteGenerator ()async
    {
      paletteGenerator = await PaletteGenerator.fromImageProvider(
        Image.asset("assets/images/8.jfif").image,
      );
    return paletteGenerator;
    }
    

    Now we can fetch it in future builder

      FutureBuilder<PaletteGenerator>(
                      future: _updatePaletteGenerator(), // async work
                      builder: (BuildContext context, AsyncSnapshot<PaletteGenerator> snapshot) {
                        switch (snapshot.connectionState) {
                          case ConnectionState.waiting: return Center(child:CircularProgressIndicator());
                          default:
                            if (snapshot.hasError)
                              return new Text('Error: ${snapshot.error}');
                            else {
                             // Color color=new Color(snapshot.data.dominantColor.color);
                              face=snapshot.data.dominantColor.color;
                               return new Text('color: ${face.toString()}');
                                  }}})
    

    This is how we can fetch dominant color easily