Want to achieve scrollable canvas in Flutter? The below Code may help to resolve your problem it scroll the custom canvas in horizontal direction as you have shown in example image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import 'package:flutter/material.dart'; class MyScroll extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Canvas Scroller'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; final height = MediaQuery.of(context).size.height; return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Center( child: new SingleChildScrollView( scrollDirection: Axis.horizontal, child: new CustomPaint( painter: new MyCanvasView(), size: new Size(width*2, height/2), ), ), ), ); } } class MyCanvasView extends CustomPainter{ @override void paint(Canvas canvas, Size size) { var paint = new Paint(); paint..shader = new LinearGradient(colors: [Colors.yellow[700], Colors.redAccent], begin: Alignment.centerRight, end: Alignment.centerLeft).createShader(new Offset(0.0, 0.0)&size); canvas.drawRect(new Offset(0.0, 0.0)&size, paint); var path = new Path(); path.moveTo(0.0, size.height); path.lineTo(1*size.width/4, 0*size.height/4); path.lineTo(2*size.width/4, 2*size.height/4); path.lineTo(3*size.width/4, 0*size.height/4); path.lineTo(4*size.width/4, 4*size.height/4); canvas.drawPath(path, new Paint()..color = Colors.yellow ..strokeWidth = 4.0 .. style = PaintingStyle.stroke); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.