Search code examples
flutterflutter-animation

How to draw a colorful background grid in flutter?


I am creating an app and I want to do a background like in this picture:

enter image description here

How can I do it by the easiest way ?


Solution

  • it use CustomPaint

    For Example

    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        getHttp();
    //
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: CustomPaint(
            painter: BacgroundPaint(),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    class BacgroundPaint extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        final height = size.height;
        final width = size.width;
        final paint = Paint();
    
        Path mainBackground = Path();
        mainBackground.addRect(Rect.fromLTRB(0, 0, width, height));
        paint.color = Colors.teal;
    
        final heightLine = height ~/ 20; // your Horizontal line
        final widthLine = (width ~/ 10); // your Vertical line
    
        for(int i = 1 ; i < height ; i++){
          if(i % heightLine == 0){
             Path linePath = Path();
             linePath.addRect(Rect.fromLTRB(0, i.toDouble(), width, (i+2).toDouble()));
             canvas.drawPath(linePath, paint);
          }
        }
        for(int i = 1 ; i < width ; i++){
          if(i % widthLine == 0){
            Path linePath = Path();
            linePath.addRect(Rect.fromLTRB(i.toDouble(), 0 , (i+2).toDouble(), height));
            canvas.drawPath(linePath, paint);
          }
        }
      }
    
      @override
      bool shouldRepaint(CustomPainter oldDelegate) {
        return oldDelegate != this;
      }
    }
    

    enter image description here