Progress Bar of flutter Wheel Project

  • 2021-12-21 04:56:53
  • OfStack

Preface

This paper records how to use CustomPaint and GestureDetector to realize a progress bar control. The first thing to note is that the flutter Material component library provides two progress indicators: LinearProgressIndicator and CircularProgressIndicator. If these two progress indicators can meet the development needs, don't try to build your own wheels. The progress bar control implemented in this paper has the following functions:

double type data with progress ranging from 0 to 1 Support dragging and get progress value through callback function Support jump. Click a certain position to jump and call back the progress value The style is Material style, which can be modified as needed

Recognize drag gestures

Using GestureDetector, you can easily monitor sliding and clicking events. The following are the four listening events, focusing on onHorizontalDragUpdate, whose callback function passes information such as coordinates of horizontal drag events to the _ seekToRelativePosition function. The _ seekToRelativePosition function calculates the value of the progress bar when sliding and updates the interface. The code is as follows:


GestureDetector(
        onHorizontalDragStart: (DragStartDetails details) {
          widget.onDragStart?.call();
        },
        onHorizontalDragUpdate: (DragUpdateDetails details) {
          widget.onDragUpdate?.call();
          _seekToRelativePosition(details.globalPosition);
        },
        onHorizontalDragEnd: (DragEndDetails details) {
          widget.onDragEnd?.call(progress);
        },
        onTapDown: (TapDownDetails details) {
          widget.onTapDown?.call(progress);
          _seekToRelativePosition(details.globalPosition);
        },
 
        // ....
 
)

_ seekToRelativePosition converts the global coordinates to the action coordinates of the progress bar control. Take the abscissa at the click, the ratio of x to the length of the progress bar control, as the value of the progress bar. Then call setState () to update the interface. Above


void _seekToRelativePosition(Offset globalPosition) {
    final box = context.findRenderObject()! as RenderBox;
    final Offset tapPos = box.globalToLocal(globalPosition);
    progress = tapPos.dx / box.size.width;
    if (progress < 0) progress = 0;
    if (progress > 1) progress = 1;
 
    setState(() {
        widget.controller.progressBarValue = progress;
    });
  } 

There is one controller control in the above code, which is defined as follows:


class VideoProgressBarController extends ChangeNotifier
{
  double progressBarValue = .0;
 
   updateProgressValue(double value){
     progressBarValue = value;
    notifyListeners();
  }
}

It inherits from ChangeNotifier because the state of this progress bar control is managed by a mixture of other controls and the control itself. When other controls want to change the value of the progress bar, you can notify the progress bar control to update the interface through VidoeProgressBarController. Of course, it will be simpler to change the progress bar control to statelesswidget, and then directly call setState () to update the interface. Readers can try it if they need it.

Drawing progress bar using CustomPaint

The drawing part is relatively simple. As follows, first draw a gray background, then draw a red progress, and then return to the dots.


class _VideoProgressBarPainter extends CustomPainter {
  _VideoProgressBarPainter(
      {required this.barHeight,
      required this.handleHeight,
      required this.value,
      required this.colors});
 
  final double barHeight;
  final double handleHeight;
  final ProgressColors colors;
  final double value;
 
  @override
  bool shouldRepaint(CustomPainter painter) {
    return true;
  }
 
  @override
  void paint(Canvas canvas, Size size) {
    final baseOffset = size.height / 2 - barHeight / 2;
    final double radius = 4.0;
 
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(size.width, baseOffset + barHeight),
        ),
        const Radius.circular(4.0),
      ),
      colors.backgroundPaint,
    );
 
    double playedPart =
        value > 1 ? size.width - radius : value * size.width - radius;
    if (playedPart < radius) {
      playedPart = radius;
    }
 
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(playedPart, baseOffset + barHeight),
        ),
        Radius.circular(radius),
      ),
      colors.playedPaint,
    );
 
    canvas.drawCircle(
      Offset(playedPart, baseOffset + barHeight / 2),
      handleHeight,
      colors.playedPaint,
    );
  }
}

Complete code:


import 'package:flutter/cupertino.dart';
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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
 
class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
 
  final String title;
 
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
 
class _MyHomePageState extends State<MyHomePage> {
  double _progressValue = .5;
  late VideoProgressBarController controller;
 
  @override
  void initState() {
    controller = VideoProgressBarController();
    super.initState();
  }
 
  @override
  Widget build(BuildContext context) {
    print("build:$_progressValue");
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(title: Text("test")),
        body: Column(
            //aspectRatio: 16 / 9,
            children: [
              Container(
                width: 200,
                height: 26,
                //color: Colors.blue,
                child: VideoProgressBar(
                  controller: controller,
                  barHeight: 2,
                  onDragEnd: (double progress) {
                    print("$progress");
                  },
                ),
              ),
              Text("value:$_progressValue"),
              ElevatedButton(
                  onPressed: (){
                      _progressValue = 1;
                      controller.updateProgressValue(_progressValue);
                  },
                  child: Text("increase")
              )
            ]
        ),
      ),
    );
  }
}
 
/// progress bar
class VideoProgressBar extends StatefulWidget {
  VideoProgressBar({
    ProgressColors? colors,
    Key? key,
    required this.controller,
    required this.barHeight,
    this.handleHeight = 6,
    this.onDragStart,
    this.onDragEnd,
    this.onDragUpdate,
    this.onTapDown,
  })  : colors = colors ?? ProgressColors(),
        super(key: key);
 
  final ProgressColors colors;
  final Function()? onDragStart;
  final Function(double progress)? onDragEnd;
  final Function()? onDragUpdate;
  final Function(double progress)? onTapDown;
 
  final double barHeight;
  final double handleHeight;
 
  final TVideoProgressBarController controller;
 
  //final bool drawShadow;
 
  @override
  _VideoProgressBarState createState() => _VideoProgressBarState();
}
 
class _VideoProgressBarState extends State<VideoProgressBar> {
  double progress = .0;
 
  @override
  void initState() {
    super.initState();
    progress = widget.controller.progressBarValue;
    widget.controller.addListener(_updateProgressValue);
  }
 
  @override
  void dispose() {
    widget.controller.removeListener(_updateProgressValue);
    super.dispose();
  }
 
  _updateProgressValue()
  {
    setState(() {
      progress = widget.controller.progressBarValue;
    });
  }
 
  void _seekToRelativePosition(Offset globalPosition) {
    final box = context.findRenderObject()! as RenderBox;
    final Offset tapPos = box.globalToLocal(globalPosition);
    progress = tapPos.dx / box.size.width;
    if (progress < 0) progress = 0;
    if (progress > 1) progress = 1;
 
    setState(() {
        widget.controller.progressBarValue = progress;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
 
    return GestureDetector(
        onHorizontalDragStart: (DragStartDetails details) {
          widget.onDragStart?.call();
        },
        onHorizontalDragUpdate: (DragUpdateDetails details) {
          widget.onDragUpdate?.call();
          _seekToRelativePosition(details.globalPosition);
        },
        onHorizontalDragEnd: (DragEndDetails details) {
          widget.onDragEnd?.call(progress);
        },
        onTapDown: (TapDownDetails details) {
          widget.onTapDown?.call(progress);
          _seekToRelativePosition(details.globalPosition);
        },
        child: Center(
          child: Container(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: CustomPaint(
                painter: _VideoProgressBarPainter(
                    barHeight: widget.barHeight,
                    handleHeight: widget.handleHeight,
                    colors: widget.colors,
                    value: progress)),
          ),
        ));
  }
}
 
class _VideoProgressBarPainter extends CustomPainter {
  _VideoProgressBarPainter(
      {required this.barHeight,
      required this.handleHeight,
      required this.value,
      required this.colors});
 
  final double barHeight;
  final double handleHeight;
  final ProgressColors colors;
  final double value;
 
  @override
  bool shouldRepaint(CustomPainter painter) {
    return true;
  }
 
  @override
  void paint(Canvas canvas, Size size) {
    final baseOffset = size.height / 2 - barHeight / 2;
    final double radius = 4.0;
 
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(size.width, baseOffset + barHeight),
        ),
        const Radius.circular(4.0),
      ),
      colors.backgroundPaint,
    );
 
    double playedPart =
        value > 1 ? size.width - radius : value * size.width - radius;
    if (playedPart < radius) {
      playedPart = radius;
    }
 
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(playedPart, baseOffset + barHeight),
        ),
        Radius.circular(radius),
      ),
      colors.playedPaint,
    );
 
    canvas.drawCircle(
      Offset(playedPart, baseOffset + barHeight / 2),
      handleHeight,
      colors.playedPaint,
    );
  }
}
 
class VideoProgressBarController extends ChangeNotifier
{
  double progressBarValue = .0;
 
   updateProgressValue(double value){
     progressBarValue = value;
    notifyListeners();
  }
}
 
class ProgressColors {
  ProgressColors({
    Color playedColor = const Color.fromRGBO(255, 0, 0, 0.7),
    Color bufferedColor = const Color.fromRGBO(30, 30, 200, 0.2),
    Color handleColor = const Color.fromRGBO(200, 200, 200, 1.0),
    Color backgroundColor = const Color.fromRGBO(200, 200, 200, 0.5),
  })  : playedPaint = Paint()..color = playedColor,
        bufferedPaint = Paint()..color = bufferedColor,
        handlePaint = Paint()..color = handleColor,
        backgroundPaint = Paint()..color = backgroundColor;
 
  final Paint playedPaint;
  final Paint bufferedPaint;
  final Paint handlePaint;
  final Paint backgroundPaint;
}

Related articles: