Jake Whittaker

Jake Whittaker

1559012629

Flutter Tutorial - Circular Slider

In this tutorial, you will learn how to integrate the GestureDetector and the Canvas to build a circular slider in Flutter. Flutter is Google’s portable UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

Have you ever wanted to spice up the usual boring sliders by providing a double handler or playing around with the layout?

If you are not that interested in how to build it but just want to get the widget and use it, you can use the package I published in .

Why do I need a circular slider?

In most cases you don’t, but imagine you want the user to select a time interval, or you just want a regular slider but want something a bit more interesting than a straight line.

What do we need in order to build it?

The first thing we need to do is create the actual slider. For this, we will draw a complete circle as the base and, on top of that, another one which will be dynamic depending on the user interaction. In order to do this we will use a special widget called CustomPaint, which provides a canvas on which we can draw what we need.

Once the slider is rendered, we need the user to be able to interact with it, so we will wrap it with a GestureDetector to capture tap and drag events.

The process will be:

  • Draw the slider
  • Recognize when the user interacts with the slider by tapping down on one of the handlers and dragging.
  • Pass the information attached to the event down to the canvas, where we will repaint the top circle.
  • Send the new values for the handlers all the way up so that the user can react to changes (i.e., updating the text in the center of the slider).

Flutter Tutorial - Circular Slider

Let’s draw some circles

First thing we need to do is draw both circles. As one of them is static (doesn’t change) and the other one dynamic (changes with user interaction), I separated them in two different painters.

Both our painters need to extend CustomPainter, a class provided by Flutter, and implement two methods: paint() and shouldRepaint(), the first one being the one to actually draw what we want and the later a way to know if we need to repaint when there is a change. For the BasePainter we never need to repaint, so it will always be false. For SliderPainter it will always be true, because every change means that the user moved the slider and the selection has to be updated.

import 'package:flutter/material.dart';

class BasePainter extends CustomPainter {
  Color baseColor;

  Offset center;
  double radius;

  BasePainter({@required this.baseColor});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
        ..color = baseColor
        ..strokeCap = StrokeCap.round
        ..style = PaintingStyle.stroke
        ..strokeWidth = 12.0;

    center = Offset(size.width / 2, size.height / 2);
    radius = min(size.width / 2, size.height / 2);

    canvas.drawCircle(center, radius, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

As you see, paint() gets a Canvas and a Size parameters. Canvas provides a set of methods that we can use to draw anything: circles, lines, arcs, rectangles, etc. Size is, well, the size of the canvas, and will be determined by the size of the widget where the canvas fits. We also need a Paint, which allows us to specify the style, color and many other things.

Now, the BasePainter is pretty self-explanatory, but the SliderPainter is a bit more tricky. Now not only need to draw an arc instead of a circle, we also need to draw the handlers.

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_circular_slider/src/utils.dart';

class SliderPainter extends CustomPainter {
  double startAngle;
  double endAngle;
  double sweepAngle;
  Color selectionColor;

  Offset initHandler;
  Offset endHandler;
  Offset center;
  double radius;

  SliderPainter(
      {@required this.startAngle,
      @required this.endAngle,
      @required this.sweepAngle,
      @required this.selectionColor});

  @override
  void paint(Canvas canvas, Size size) {
    if (startAngle == 0.0 && endAngle == 0.0) return;

    Paint progress = _getPaint(color: selectionColor);

    center = Offset(size.width / 2, size.height / 2);
    radius = min(size.width / 2, size.height / 2);

    canvas.drawArc(Rect.fromCircle(center: center, radius: radius),
        -pi / 2 + startAngle, sweepAngle, false, progress);

    Paint handler = _getPaint(color: selectionColor, style: PaintingStyle.fill);
    Paint handlerOutter = _getPaint(color: selectionColor, width: 2.0);

    // draw handlers
    initHandler = radiansToCoordinates(center, -pi / 2 + startAngle, radius);
    canvas.drawCircle(initHandler, 8.0, handler);
    canvas.drawCircle(initHandler, 12.0, handlerOutter);

    endHandler = radiansToCoordinates(center, -pi / 2 + endAngle, radius);
    canvas.drawCircle(endHandler, 8.0, handler);
    canvas.drawCircle(endHandler, 12.0, handlerOutter);
  }

  Paint _getPaint({@required Color color, double width, PaintingStyle style}) =>
      Paint()
        ..color = color
        ..strokeCap = StrokeCap.round
        ..style = style ?? PaintingStyle.stroke
        ..strokeWidth = width ?? 12.0;

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

Again, we get the center and radius, but now we draw an arc. Our SliderPainter will get as parameters the start, end and sweep angle to use based on the user interactions, so we can use those to draw the arc. The only thing worth mention here is that we need to subtract -pi/2 radians from the initial angle because our slider origin is on the top of the circle and the drawArc() function uses the positive x axis instead.

Once we have the arc we need to draw the handlers. For that we will draw two circles for each, an internal filled one and an external around it. I’m using some utility functions to translate from radians to coordinates in the circle. You can check these functions in the repo in github.

How do we make it interactive?

What we have right now would be enough to draw what we want, we just need to use CustomPaint and both our painters, but it’s still not interactive. We need to wrap it with a GestureDetector. That way we will be able to react to user events in the canvas.

We will define initial values for our handlers and then, as we know the coordinates for those handlers, our strategy will be as follows:

  • listen for a pan (tap) down on any of the handlers and update the status for that handler (_xHandlerSelected = true).
  • listen for a pan (drag) update event while any handler is selected, and then update the coordinates for that handler and pass them down to the SliderPainter and up in our callback method.
  • listen for a pan (tap) up event and reset the status of the handlers to not selected.

As we need to calculate the coordinates for the handlers and the new angles to pass down to the painter, our CircularSliderPaint has to be a StatefulWidget.

import 'package:flutter/material.dart';
import 'package:flutter_circular_slider/src/base_painter.dart';
import 'package:flutter_circular_slider/src/slider_painter.dart';
import 'package:flutter_circular_slider/src/utils.dart';

class CircularSliderPaint extends StatefulWidget {
  final int init;
  final int end;
  final int intervals;
  final Function onSelectionChange;
  final Color baseColor;
  final Color selectionColor;
  final Widget child;

  CircularSliderPaint(
      {@required this.intervals,
      @required this.init,
      @required this.end,
      this.child,
      @required this.onSelectionChange,
      @required this.baseColor,
      @required this.selectionColor});

  @override
  _CircularSliderState createState() => _CircularSliderState();
}

class _CircularSliderState extends State {
  bool _isInitHandlerSelected = false;
  bool _isEndHandlerSelected = false;

  SliderPainter _painter;

  /// start angle in radians where we need to locate the init handler
  double _startAngle;

  /// end angle in radians where we need to locate the end handler
  double _endAngle;

  /// the absolute angle in radians representing the selection
  double _sweepAngle;

  @override
  void initState() {
    super.initState();
    _calculatePaintData();
  }

  // we need to update this widget both with gesture detector but
  // also when the parent widget rebuilds itself
  @override
  void didUpdateWidget(CircularSliderPaint oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.init != widget.init || oldWidget.end != widget.end) {
      _calculatePaintData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanDown: _onPanDown,
      onPanUpdate: _onPanUpdate,
      onPanEnd: _onPanEnd,
      child: CustomPaint(
        painter: BasePainter(
            baseColor: widget.baseColor,
            selectionColor: widget.selectionColor),
        foregroundPainter: _painter,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: widget.child,
        ),
      ),
    );
  }

  void _calculatePaintData() {
    double initPercent = valueToPercentage(widget.init, widget.intervals);
    double endPercent = valueToPercentage(widget.end, widget.intervals);
    double sweep = getSweepAngle(initPercent, endPercent);

    _startAngle = percentageToRadians(initPercent);
    _endAngle = percentageToRadians(endPercent);
    _sweepAngle = percentageToRadians(sweep.abs());

    _painter = SliderPainter(
      startAngle: _startAngle,
      endAngle: _endAngle,
      sweepAngle: _sweepAngle,
      selectionColor: widget.selectionColor,
    );
  }

  _onPanUpdate(DragUpdateDetails details) {
    if (!_isInitHandlerSelected && !_isEndHandlerSelected) {
      return;
    }
    if (_painter.center == null) {
      return;
    }
    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);

    var angle = coordinatesToRadians(_painter.center, position);
    var percentage = radiansToPercentage(angle);
    var newValue = percentageToValue(percentage, widget.intervals);

    if (_isInitHandlerSelected) {
      widget.onSelectionChange(newValue, widget.end);
    } else {
      widget.onSelectionChange(widget.init, newValue);
    }
  }

  _onPanEnd(_) {
    _isInitHandlerSelected = false;
    _isEndHandlerSelected = false;
  }

  _onPanDown(DragDownDetails details) {
    if (_painter == null) {
      return;
    }
    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);
    if (position != null) {
      _isInitHandlerSelected = isPointInsideCircle(
          position, _painter.initHandler, 12.0);
      if (!_isInitHandlerSelected) {
        _isEndHandlerSelected = isPointInsideCircle(
            position, _painter.endHandler, 12.0);
      }
    }
  }
}

A few things to notice here:

  • We want to notify the parent widget when the position of the handlers (and hence, the selection) is updated, that’s why the widget exposes a callback function onSelectionChange().
  • The widget needs to be re-rendered when the user interacts with the slider, but also if the initial parameters change, that’s why we use didUpdateWidget().
  • CustomPaint also allows a child parameter, so we can use that to render something inside our circle. We will just expose the same parameter in our final widget so that the user can pass whatever she wants.
  • We use intervals to set the number of possible values in the slider. With that we can conveniently express the selection as a percentage.
  • Again, I use different utility functions to translate between percentages, radians and coordinates. The coordinates system in a canvas is a bit different to a regular one, as it starts in the top left corner and so both x and y are always positive values. Also, radians start in the positive x axis and go clockwise (always positive) from 0 to 2*pi radians.
  • Finally, the coordinates for our handlers are related to the canvas origin, but the coordinates in GestureDetector are global to the device, so we need to transform those using RenderBox.globalToLocal() which uses the context in a widget as a reference.

With this we have all we need for our circular slider.

A few extra features

There’s quite a few ground to cover here so I didn’t go full into details, but you can check the repo for the project and I’ll be glad to answer any question in the comments.

In the final version I added some extra features, like custom colors for the selection and the handlers or the option to draw primary and secondary selectors to get that great look for the watch (hours, minutes) if we need it. I also wrapped everything in a final widget for clarity.

Remember you can also use this widget if you want by importing the library from .

#flutter

What is GEEK

Buddha Community

Flutter Tutorial - Circular Slider

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Adobe XD plugin for Flutter with CodePen Tutorial

Recently Adobe XD releases a new version of the plugin that you can use to export designs directly into flutter widgets or screens. Yes, you read it right, now you can make and export your favorite design in Adobe XD and export all the design in the widget form or as a full-screen design, this can save you a lot of time required in designing.

What we will do?
I will make a simple design of a dialogue box with a card design with text over it as shown below. After you complete this exercise you can experiment with the UI. You can make your own components or import UI kits available with the Adobe XD.

#developers #flutter #adobe xd design export to flutter #adobe xd flutter code #adobe xd flutter code generator - plugin #adobe xd flutter plugin #adobe xd flutter plugin tutorial #adobe xd plugins #adobe xd to flutter #adobe xd tutorial #codepen for flutter.

Flutter Tutorial - Cloud Firestore🔥 | Flutter Firestore CRUD | Flutter Firestore Tutorial

Here I am with yet another great video with a lot of learning potential. Not like others! It is all detailed and I tried my best to explain all the CRUD operations.

Subscribe to show some love!

https://youtu.be/lyZQa7hqoVY

#flutter #flutter-firestore #flutter-tutorial #firestore-tutorial #firestore-crud

Kaia  Schmitt

Kaia Schmitt

1627110000

GetX Flutter Tutorials - Part I | Route Management | Flutter Tutorials | GetX | Flutter

GetX Flutter Tutorials - Route Management
GitHub - https://github.com/theindianinnovation/GETX_TUTORIAL1

#flutter #getx #flutter tutorials #route management #getx flutter tutorials