Flutter 怎么实现类似于 AppleMusic 根据图片生成背景渐变色的效果

12 min read
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Color(0xfffc00ff),
                Color(0xff00c4ff),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

如果想从图片中提取颜色,你可以使用库,例如color_thief_flutter

这是代码示例:

Future<void> _getImageAndSetGradient() async {
  final image = await ImagePicker.pickImage(source: ImageSource.gallery);
  if (image == null) return;

  final colorThief = ColorThief();
  final colors = await colorThief.getColor(image.path, quality: 10);
  setState(() {
    _gradient = LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        Color(colors[0]),
        Color(colors[1]),
      ],
    );
  });
}