Created
March 9, 2020 20:25
-
-
Save miquelbeltran/f79046e2aa03ac171af1543a6bfa151a to your computer and use it in GitHub Desktop.
Generate a color gradient grid in Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: Scaffold(body: ColorGrid()), | |
); | |
} | |
} | |
class ColorGrid extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final colorA = Colors.green; | |
final colorB = Colors.blueGrey; | |
final colorC = Colors.lightGreenAccent; | |
final colorD = Colors.greenAccent; | |
final numRows = 10; | |
final numCols = 10; | |
final h = MediaQuery.of(context).size.height / numCols; | |
final w = MediaQuery.of(context).size.width / numRows; | |
int interpolate(int a, int b, int c, int d, double t, double s) { | |
return (a * (1 - t) * (1 - s) + | |
b * t * (1 - s) + | |
c * (1 - t) * s + | |
d * t * s) | |
.floor(); | |
} | |
Widget Function(int) generator2(double t) { | |
return (int index) { | |
final s = index / numCols; | |
return Container( | |
color: Color.fromRGBO( | |
interpolate(colorA.red, colorB.red, colorC.red, colorD.red, t, s), | |
interpolate( | |
colorA.green, colorB.green, colorC.green, colorD.green, t, s), | |
interpolate( | |
colorA.blue, colorB.blue, colorC.blue, colorD.blue, t, s), | |
1.0, | |
), | |
height: h, | |
width: w, | |
); | |
}; | |
} | |
Widget generator(int index) { | |
final t = index / numRows; | |
return Row( | |
children: List<Widget>.generate(numCols, generator2(t)), | |
); | |
} | |
return Column( | |
children: List<Widget>.generate(numRows, generator), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment