Latest source merged from Syncfusion

This commit is contained in:
pipeline 2021-06-29 23:57:39 +05:30
Родитель 3804c3dfcb
Коммит d486bfd1c6
94 изменённых файлов: 91 добавлений и 24397 удалений

Просмотреть файл

@ -1,107 +0,0 @@
---
layout: post
title: Accessibility in Flutter Date Range Picker widget | Syncfusion
description: Learn here all about Accessibility feature of Syncfusion Flutter Date Range Picker (SfDateRangePicker) widget and more.
platform: flutter
control: SfDateRangePicker
documentation: ug
---
# Accessibility in Flutter DateRangePicker (SfDateRangePicker)
## Screen reader support
The `SfDateRangePicker` can easily be accessed by screen readers. Please find the following table to get spoken feedback about the inner element contents of the screen.
### Month view
| View | Format | Example |
|-------------------------------------------------------------------|----------------------------------|------------------------------------------|
| Month cell | EEE, dd/MMMM/yyyy | Thursday the 2nd of January 2020 |
| Month header | MMMM yyyy | January 2020 |
| View header | EEE | Monday |
| Disabled cells (Enable dates in past, dates exceed min/max dates) | EEE, dd/MMMM/yyyy, Disabled date | Friday, 31st January 2020, Disabled date |
| Blackout date | EEE, dd/MMMM/yyyy, blackout date | 6th February 2020, Blackout date |
### Year view
| View | Format | Example |
|------------------------------------------------------------------|--------------------------|------------------------------|
| Year cell | MMMM yyyy | January 2020 |
| Header | yyyy | 2020 |
| Disabled cell (Enable dates in past, dates exceeds min/max date) | MMMM yyyy, Disabled cell | December 2019, Disabled cell |
### Decade view
| View | Format | Example |
|------------------------------------------------------------------|---------------------|--------------------|
| Header | yyyy - yyyy | 2020 to 2029 |
| Decade cell | yyyy | 2020 |
| Disabled cell (Enable dates in past, dates exceeds min/max date) | yyyy, Disabled cell | 2019 Disabled cell |
### Century view
| View | Format | Example |
|------------------------------------------------------------------|-------------|-----------------------------|
| Header | yyyy - yyyy | 2020 to 2029 |
| Century cell | yyyy - yyyy | 2020 to 2029 |
| Disabled cell (Enable dates in past, dates exceeds min/max date) | yyyy - yyyy | 2010 to 2019, Disabled cell |
### Navigation arrows
| View | Format | Example |
|---------------------------|--------|-----------------|
| Forward navigation arrow | > | Forward button |
| Backward navigation arrow | < | Backward button |
## Sufficient contrast
The `SfDateRangePicker` [theming](https://help.syncfusion.com/flutter/themes/themes) support offers a consistent and standardized look, as well as the ability to set the colors for all UI elements.
The following APIs allows to customize the colors of the following elements.
* [viewHeaderStyle](https://help.syncfusion.com/flutter/daterangepicker/headers#view-header)
* [headerStyle](https://help.syncfusion.com/flutter/daterangepicker/headers#header-appearance)
* [leadingDatesDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [trailingDatesDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [cellDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [blackoutDatesDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [specialDatesDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [weekendDatesDecoration](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [selectionColor](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
* [startRangeSelectionColor](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
* [endRangeSelectionColor](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
* [rangeSelectionColor](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
* [yearCellStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#year-cell-customization)
## Large fonts
The `SfDateRangePicker` font size can be adjusted automatically based on device settings and the font size scaled based on the `MediaQueryData.textScaleFactor`. And also it allows to change the font size of all elements in date range picker.
* [todayTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations)
* [leadingDatesTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations)
* [trailingDatesTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations)
* [disabledDatesTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations)
* [textStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations)
* [blackoutDateTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [specialDatesTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [weekendTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#month-cell-customization)
* [selectionTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
* [rangeTextStyle](https://help.syncfusion.com/flutter/daterangepicker/customizations#selection-cell-customization)
## Keyboard navigation
The following keyboard interactions are supported by the `SfDateRangePicker`.
| Key | Description |
|-----------------------|--------------------------------------------------------------------------------------------------------|
| Up arrow | Selects the same day of the previous week |
| Down arrow | Selects the same day of the next week |
| Right arrow | Selects the day after |
| Left arrow | Selects the day before |
| Alt+1 | Displays month view |
| Alt+2 | Displays year view |
| Alt+3 | Displays decade view |
| Alt+4 | Displays century view |
| Tap | Focuses the next clickable element |
| Shift + upper arrow | Selects the same day in previous week to complete range selection or add the day in multiple selection |
| Shift + down arrow | Selects the same day in next week to complete range selection or add the day in multiple selection |
| Shift + left arrow | Selects the day before to complete range selection or add the day in multiple selection |
| Shift + right arrow | Selects the day after to complete range selection or add the day in multiple selection |

Просмотреть файл

@ -1,418 +0,0 @@
---
layout: post
title: About Flutter Hijri Date Range Picker widget | Syncfusion | DatePicker
description: Learn here all about introduction of Syncfusion Hijri Date Range Picker (SfHijriDateRangePicker) widget and more.
platform: flutter
control: SfDateRangePicker
documentation: ug
---
# Flutter Hijri Date Range Picker (SfHijriDateRangePicker) Overview
Along with the Gregorian calendar, the picker package contains a Hijri date picker to display the Islamic calendar. Islamic calendar or Hijri calendar is a lunar calendar consisting of 12 months in a year of 354 or 355 days. To know more about the Islamic calendar, kindly refer to [Wikipedia](https://en.wikipedia.org/wiki/Islamic_calendar).
It consists of all the Gregorian calendar functionalities like min and max date, the first day of the week, different selection modes, RTL, and customization for special dates.
To display the Hijri date picker, initialize the [HijriDateRangePicker](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker-class.html) widget as a child of any widget. Here, the Hijri date range picker added as a child of the scaffold widget.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(body: SfHijriDateRangePicker()),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri date range picker](images/hijri-picker/hijri_programattic_view_navigation.jpg)
>**NOTE**
* Most of the properties type and classes were same from [SfDateRangePicker](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker-class.html) except the followings [HijriDatePickerController](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerController-class.html), [HijriDatePickerMonthCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle-class.html), [HijriDatePickerMonthViewSettings](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthViewSettings-class.html), [HijriDatePickerViewChangedArgs](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerViewChangedArgs-class.html), [HijriDatePickerYearCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle-class.html), [HijriDateRange](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDateRange-class.html) and [HijriDatePickerView](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerView-class.html).
* Use the [HijriDateTime](https://pub.dev/documentation/syncfusion_flutter_core/latest/core/HijriDateTime-class.html) class to define the date for `SfHijriDateRangePicker`.
## Multiple picker views
The `SfHijriDateRangePicker` widget provides three different types of views to display. It can be assigned to the widget constructor by using the [view](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/view.html) property. The default view of the widget is the month view. By default, the current date will be displayed initially for all the date range picker views.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
view: HijriDatePickerView.year,
)),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri multiple picker views](images/hijri-picker/hijri_picker_views.png)
## Change first day of week
The `SfHijriDateRangePicker` widget will be rendered with Sunday as the first day of the week but you can customize it to any day by using the [firstDayOfWeek](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthViewSettings/firstDayOfWeek.html) property [HijriDatePickerMonthViewSettings](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthViewSettings-class.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
view: HijriDatePickerView.month,
monthViewSettings: HijriDatePickerMonthViewSettings(firstDayOfWeek: 1),
)),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri first day of week](images/hijri-picker/hijri_first_day_of_week.png)
## Date selection
The `SfHijriDateRangePicker` supports selecting single, multiple, and range of dates. It also supports the programmatic selection.
The selected date or range details can be obtained using the [onSelectionChanged ](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/onSelectionChanged.html)callback of Hijri date range picker. The callback will return the [DateRangePickerSelectionChangedArgs](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerSelectionChangedArgs-class.html), which contains the selected date or range details.
{% tabs %}
{% highlight Dart %}
void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
/// TODO: implement your code here
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
view: HijriDatePickerView.month,
selectionMode: DateRangePickerSelectionMode.range,
onSelectionChanged: _onSelectionChanged,
)),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri date selection](images/hijri-picker/hijri_progrmatic_selection_range.png)
## Programmatic date navigation
You can programmatically navigate date in the Hijri date picker widget by using the [displayDate](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerController/displayDate.html) property from [HijriDatePickerController](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerController-class.html).
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.displayDate = HijriDateTime(1445, 02, 05);
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
controller: _controller,
view: HijriDatePickerView.month,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic date navigation](images/hijri-picker/hijri_programattic_date_navigation.png)
## Programmatic view navigation
You can programmatically navigate to any view in the Hijri date picker widget by using the [view](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerController/view.html) property of `HijriDatePickerController.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.view = HijriDatePickerView.month;
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
controller: _controller,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic view navigation](images/hijri-picker/hijri_programattic_view_navigation.jpg)
## Programmatic date selection
You can select dates programmatically on the Hijri date picker widget by using the `HijriDatePickerController`.
For selection [refer](https://help.syncfusion.com/flutter/daterangepicker/selections).
### Single selection
You can select the date programmatically by using the [selectedDate](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerController/selectedDate.html) property of `HijriDatePickerController`. It is only applicable when the `selectionMode` is set to `DateRangePickerSelectionMode.single`.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.view = HijriDatePickerView.month;
_controller.selectedDate = HijriDateTime.now().add(Duration(days: 1));
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
selectionMode: DateRangePickerSelectionMode.single,
controller: _controller,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic single selection](images/hijri-picker/hijri_programmatic_selection_single.png)
### Multi selection
You can select the multiple dates programmatically by using the [selectedDates](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerController/selectedDates.html) property of `HijriDatePickerController`. It is only applicable when the selectionMode is set to `DateRangePickerSelectionMode.multiple`.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.view = HijriDatePickerView.month;
_controller.selectedDates = <HijriDateTime>[
HijriDateTime.now().add(Duration(days: 2)),
HijriDateTime.now().add(Duration(days: 4)),
HijriDateTime.now().add(Duration(days: 7)),
HijriDateTime.now().add(Duration(days: 11))
];
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
selectionMode: DateRangePickerSelectionMode.multiple,
controller: _controller,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic multi selection](images/hijri-picker/hijri_programmatic_selection_multiple.png)
### Range selection
You can select the single date range programmatically by using the [selectedRange](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerController/selectedRange.html) property of `HijriDatePickerController`. It is only applicable when the `selectionMode` is set to `DateRangePickerSelectionMode.range`.
Use the [HijriDateRange](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDateRange-class.html) to define the date range for the Hijri date picker.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.view = HijriDatePickerView.month;
_controller.selectedRange = HijriDateRange(
HijriDateTime(1442, 03, 01), HijriDateTime(1442, 03, 05));
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
selectionMode: DateRangePickerSelectionMode.range,
controller: _controller,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic range selection](images/hijri-picker/hijri_progrmatic_selection_range.png)
### Multi-range selection
You can select more than one date range programmatically by using the [selectedRanges](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerController/selectedRanges.html) property of `HijriDatePickerController`. It is only applicable when the `selectionMode` is set to `DateRangePickerSelectionMode.multiRange`.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
HijriDatePickerController _controller = HijriDatePickerController();
@override
void initState() {
_controller.view = HijriDatePickerView.month;
_controller.selectedRanges = <HijriDateRange>[
HijriDateRange(HijriDateTime.now().add(Duration(days: 4)),
HijriDateTime.now().add(Duration(days: 9))),
HijriDateRange(HijriDateTime.now().add(Duration(days: 11)),
HijriDateTime.now().add(Duration(days: 16)))
];
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
selectionMode: DateRangePickerSelectionMode.multiRange,
controller: _controller,
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Hijri programmatic multi-range selection](images/hijri-picker/hijri_programmatic_selection_multi_range.png)
## Month cell customization
You can customize the Hijri date picker month view by using the [monthCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/monthCellStyle.html) property of `SfHijriDateRangePicker`.
**Current month dates**: You can customize the current month dates text style and background of the `SfHijriDateRangePicker` by using the [textStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/textStyle.html) and [cellDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/cellDecoration.html) properties of [HijriDatePickerMonthCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle-class.html).
**Today date**: You can customize the today date text style and background of the `SfHijriDateRangePicker` by using the [todayTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/todayTextStyle.html) and [todayCellDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/todayCellDecoration.html).
**Blackout Dates**: You can customize the blackout dates text style and background of the `SfHijriDateRangePicker` by using the [blackoutDateTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/blackoutDateTextStyle.html) and [blackoutDatesDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/blackoutDatesDecoration.html).
**Disabled dates**: Disable the dates text style and background beyond of the [minDate](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/minDate.html) and [maxDate](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/maxDate.html) in `SfHijriDateRangePicker` by using the [disableDatesTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/disabledDatesTextStyle.html) and [disableDatesDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/disabledDatesDecoration.html).
**Special Dates**: You can add special dates to the `SfHijriDateRangePicker` by using the [specialDates](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthViewSettings/specialDates.html) property, and you can also customize the special dates text style and background by using the [specialDatesTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/specialDatesTextStyle.html) and [specialDatesDecoration]().
**Weekend Dates**: You can change the weekend dates to `SfHijriDateRangePicker` by using the [weekendDays](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthViewSettings/weekendDays.html) property, and you can also customize the weekend dates text style and background by using the [weekendDatesTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/weekendTextStyle.html) and [weekendDatesDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerMonthCellStyle/weekendDatesDecoration.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
view: HijriDatePickerView.month,
monthViewSettings: HijriDatePickerMonthViewSettings(
blackoutDates: <HijriDateTime>[HijriDateTime(1442, 02, 05)],
weekendDays: <int>[6, 7],
specialDates: <HijriDateTime>[
HijriDateTime(1442, 02, 10),
HijriDateTime(1442, 02, 15)
],
),
monthCellStyle: HijriDatePickerMonthCellStyle(
blackoutDatesDecoration: BoxDecoration(
color: Colors.red,
border: Border.all(color: const Color(0xFFF44436), width: 1),
shape: BoxShape.circle),
weekendDatesDecoration: BoxDecoration(
color: const Color(0xFFDFDFDF),
border: Border.all(color: const Color(0xFFB6B6B6), width: 1),
shape: BoxShape.circle),
specialDatesDecoration: BoxDecoration(
color: Colors.green,
border: Border.all(color: const Color(0xFF2B732F), width: 1),
shape: BoxShape.circle),
blackoutDateTextStyle: TextStyle(
color: Colors.white, decoration: TextDecoration.lineThrough),
specialDatesTextStyle: const TextStyle(color: Colors.white),
),
)),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri month cell customization](images/hijri-picker/hijri_month_customization.png)
## Year cell customization
You can customize the calendar year, and decade view by using the [yearCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfHijriDateRangePicker/yearCellStyle.html) of `SfHijriDateRangePicker`.
**Current year**: You can customize the current month dates text style and background of the `SfHijriDateRangePicker` by using the [textStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/textStyle.html) and [cellDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/cellDecoration.html) properties of [HijriDatePickerYearCellStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle-class.html).
**Disabled dates**: Disable the dates text style and background of the `SfHijriDateRangePicker` by using the [disableDatesTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/disabledDatesTextStyle.html) and [disableDatesDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/disabledDatesDecoration.html).
**Today date**: You can customize the today date text style and background of the `SfHijriDateRangePicker` by using the [todayTextStyle](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/todayTextStyle.html) and [todayCellDecoration](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/HijriDatePickerYearCellStyle/todayCellDecoration.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfHijriDateRangePicker(
view: HijriDatePickerView.year,
yearCellStyle: HijriDatePickerYearCellStyle(
disabledDatesDecoration: BoxDecoration(
color: const Color(0xFFDFDFDF),
border: Border.all(color: const Color(0xFFB6B6B6), width: 1),
shape: BoxShape.circle),
disabledDatesTextStyle: const TextStyle(color: Colors.black),
textStyle: const TextStyle(color: Colors.blue),
todayCellDecoration: BoxDecoration(
color: const Color(0xFFDFDFDF),
border: Border.all(color: const Color(0xFFB6B6B6), width: 1),
shape: BoxShape.circle),
todayTextStyle: const TextStyle(color: Colors.purple),
),
)),
);
}
{% endhighlight %}
{% endtabs %}
![Hijri year cell customization](images/hijri-picker/hijri_year_customization.png)
## See also
[How to use Hijri date range picker (SfHijriDateRangePicker) in Flutter](https://www.syncfusion.com/kb/12200/how-to-use-hijri-date-range-picker-sfhijridaterangepicker-in-flutter)

Просмотреть файл

@ -1,215 +0,0 @@
---
layout: post
title: Selections in Flutter Date Range Picker widget | Syncfusion
description: Learn here all about Selections feature in Syncfusion Flutter Date Range Picker (SfDateRangePicker) widget and more.
platform: Flutter
control: SfDateRangePicker
documentation: ug
---
# Selections in Flutter Date Range Picker (SfDateRangePicker)
Dates can be selected by touching the on month view cells. The default [selectionMode](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/selectionMode.html) is Single that allows the user to select one date at a time. `SfDateRangePicker` provides support to select dates in four modes such as `Single`, `Multiple`, `Range` and `MultiRange` selection
>**NOTE** When the `enableViewNavigation` property is set to false, the Date range picker allows you to select the cells in the year, decade, and century views of date range picker.
## Single selection
A `single` date range picker cell can be selected in a date range picker view by setting the [DateRangePickerSelectionMode](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerSelectionMode-class.html) to `single`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.single,
)
);
}
{% endhighlight %}
{% endtabs %}
![SingleSelection Date Range Picker](images/selections/singleselection.jpg)
>**NOTE**
* The year, decade, and century view allow you to select cells only when the `enableViewNavigation` is set to false.
* In this scenario, the `selection changed` callback will return the first date of the month, year, or decade of the selected cell when the selection mode set to `single` and `multiple`.
Eg:
* In the year view, when the May month cell is selected then the selected date value will be 01-05-2020.
* In the decade view, when the (2025) year cell is selected then the selected date value will be 01-01-2025.
* In the century view, when the (2020-2029) decade cell is selected then the selected date value will be 01-01-2020.
## Multiple selection
You can randomly select more than one date range picker cell by setting the `DateRangePickerSelectionMode` to `multiple`. By Clicking again you can deselect the selected cells.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.multiple,
)
);
}
{% endhighlight %}
{% endtabs %}
![MultiSelection Date Range Picker](images/selections/multiselection.jpg)
## Range selection
You can select a range of cells in any date range picker view by setting the `DateRangePickerSelectionMode` to the `range`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.range,
)
);
}
{% endhighlight %}
{% endtabs %}
![RangeSelection Date Range Picker](images/selections/range-selection.jpg)
>**NOTE**
* The year, decade, and century view allow you to select cells only when the `enableViewNavigation` set is as false.
* In this scenario, the `selection changed` callback will return the first and last date of the month, year, or decade of the selected cell when the selection mode is set to `range` and `multi-range`.
Eg:
* In the year view, when the range is selected as May – June, then the range value will be 01-05-2020 to 30-06-2020.
* In the decade view, when the range is selected as 2025 – 2030, then the range value will be 01-01-2025 to 31-12-2030.
* In the century view, when the range is selected as 2020-2029 to 2030-2039, then the range value will be 01-01-2020 to 31-12-2039.
## Multi range selection
You can select more than one range of cells in any of the date range picker views by setting the `DateRangePickerSelectionMode` to the `multiRange`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.multiRange,
)
);
}
{% endhighlight %}
{% endtabs %}
![MultiRangeSelection Date Range Picker](images/selections/multirange.jpg)
## Selection radius
You can customize the radius of the selection using the [selectionRadius](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/selectionRadius.html) property of the `SfDateRangePicker`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionRadius: 10,
),
);
}
{% endhighlight %}
{% endtabs %}
![Selection radius Date Range Picker](images/selections/selectionradius.png)
## Selection shape
You can customize the selection shape of the selected date using the [selectionShape](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/selectionShape.html) property of the `DateRangePicker`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionShape: DateRangePickerSelectionShape.rectangle,
),
);
}
{% endhighlight %}
{% endtabs %}
![Selection shape Date Range Picker](images/selections/selectionshape.png)
## Enable swipe selection
Using the [enableSwipeSelection](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerMonthViewSettings/enableSwipeSelection.html) property of the `DateRangePicker`, you can select the dates by using swiping. By default, `enableSwipeSelection` property as `true`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.range,
monthViewSettings:
DateRangePickerMonthViewSettings(enableSwipeSelection: false),
),
);
}
{% endhighlight %}
{% endtabs %}
## Toggle day selection
You can deselect the selected date using the [toggleDaySelection](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/toggleDaySelection.html) property of the `SfDateRangePicker`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
toggleDaySelection: true,
),
);
}
{% endhighlight %}
{% endtabs %}
## See also
[How to restrict swipe gesture for range selection in Flutter date range picker (SfDateRangePicker)?](https://www.syncfusion.com/kb/12117/how-to-restrict-swipe-gesture-for-range-selection-in-flutter-date-range-picker)
[How to change the selection radius in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12230/how-to-change-the-selection-radius-in-the-flutter-date-range-picker-sfdaterangepicker)
[How to add an image as background in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12233/how-to-add-an-image-as-background-in-the-flutter-date-range-picker-sfdaterangepicker)
[How to get the start and end date of the selected range in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12248/how-to-get-the-start-and-end-date-of-the-selected-range-in-the-flutter-date-range-picker)
[How to change the selection shape in Flutter date range picker (SfDateRangePicker)?](https://www.syncfusion.com/kb/11900/how-to-change-the-selection-shape-in-flutter-date-range-picker-sfdaterangepicker)
[How to deselect the selected date in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12138/how-to-deselect-the-selected-date-in-the-flutter-date-range-picker-sfdaterangepicker)
[How to select previous or next dates based on the selected date in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12354/how-to-select-previous-or-next-dates-based-on-the-selected-date-in-the-flutter-date-range)
[How to select all days when clicking on the day header in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12353/how-to-select-all-days-when-clicking-on-the-day-header-in-the-flutter-date-range-picker)

Просмотреть файл

@ -1,170 +0,0 @@
---
layout: post
title: Views in Flutter Date Range Picker widget | Syncfusion
description: Learn here all about Views feature of Syncfusion Flutter Date Range Picker (SfDateRangePicker) widget and more.
platform: Flutter
control: SfDateRangePicker
documentation: ug
---
# Multiple Picker Views in Flutter Date Range Picker (SfDateRangePicker)
The `SfDateRangePicker` widget provides four different types of views to display. It can be assigned to the widget constructor by using the [view](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/view.html) property. Default view of the widget is month view. By default the current date will be displayed initially for all the date range picker views.
## Month view
This view displays the entire dates of a particular month. By default , the current month will be displayed on loading. The current date is provided with a separate color different from the rest of the dates color in `month view`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
)
);
}
{% endhighlight %}
{% endtabs %}
![Month view Date Range Picker](images/views/monthview.png)
## Year view
This displays the entire month of a particular year. By default, the current year will be displayed on loading. You can navigate between months quickly by selecting the particular month in a `year view`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.year,
)
);
}
{% endhighlight %}
{% endtabs %}
![Year view Date Range Picker](images/views/yearview.png)
## Decade view
This view displays the period of 10 years. By default, the current year range of 10 years will be displayed on loading. You can easily navigate between month/year view to decade view by tapping the calendar header. The year can be navigated quickly by selecting a particular year from a `decade view`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.decade,
)
);
}
{% endhighlight %}
{% endtabs %}
![Decade view Date Range Picker](images/views/decadeview.png)
## Century view
This view displays the period of 100 years. By default, the current year range of 100 years will be displayed on loading. You can easily navigate between month/year/decade view to century view by tapping the calendar header. You can easily navigate to a decade view by selecting decade years in `century view`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.century,
)
);
}
{% endhighlight %}
{% endtabs %}
![Century view Date Range Picker](images/views/centuryview.png)
## Week view
The number of weeks in the month view can be customized by setting the [numberOfWeeksInView](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerMonthViewSettings/numberOfWeeksInView.html) property of [DateRangePickerMonthViewSettings](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/DateRangePickerMonthViewSettings-class.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDateRangePicker(
view: DateRangePickerView.month,
monthViewSettings:
DateRangePickerMonthViewSettings(numberOfWeeksInView: 2)),
);
}
{% endhighlight %}
{% endtabs %}
![Century view Date Range Picker](images/views/numberofweek-in-view.png)
## Multi-date picker view
You can enable a multi-date range picker by using the [enableMultiView](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/enableMultiView.html) property of `SfDateRangePicker`, which displays two date range pickers side by side, the space between the two date-range picker can be customized by using the [viewSpacing](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/viewSpacing.html) property of `SfDateRangePicker`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfDateRangePicker(
enableMultiView: true,
viewSpacing: 20,
headerStyle: DateRangePickerHeaderStyle(
textAlign: TextAlign.center
),
));
}
}
{% endhighlight %}
{% endtabs %}
![Multi-date picker view](images/views/multi-picker-view.jpg)
### Vertical picker
You can arrange the two date range picker views in the vertical direction by setting the [navigationDirection](https://pub.dev/documentation/syncfusion_flutter_datepicker/latest/datepicker/SfDateRangePicker/navigationDirection.html) as `DateRangePickerNavigationDirection.vertical` in the `SfDateRangePicker`.`
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfDateRangePicker(
enableMultiView: true,
navigationDirection: DateRangePickerNavigationDirection.vertical,
viewSpacing: 10,
)),
);
}
{% endhighlight %}
{% endtabs %}
![vertical date picker](images/views/vertical-datepicker.png)
## See also
[How to switch between the date range picker views in the Flutter date range picker (SfDateRangePicker)?](https://www.syncfusion.com/kb/11305/how-to-switch-between-the-date-range-picker-views-in-flutter-date-range-picker)
[How to get the current view dates in Flutter date range picker (SfDateRangePicker)?](https://www.syncfusion.com/kb/11331/how-to-get-the-current-view-dates-in-flutter-date-range-picker-sfdaterangepicker)
[How to show two pickers vertically in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12193/how-to-show-two-pickers-vertically-in-the-flutter-date-range-picker-sfdaterangepicker)
[How to change the number of weeks in the Flutter date range picker (SfDateRangePicker)](https://www.syncfusion.com/kb/12167/how-to-change-the-number-of-weeks-in-the-flutter-date-range-picker-sfdaterangepicker)

Просмотреть файл

@ -1,91 +0,0 @@
---
layout: post
title: Accessibility in Flutter Event Calendar widget | Syncfusion
description: Learn here all about accessibility feature of Syncfusion Flutter Calendar (SfCalendar) widget and more.
platform: flutter
control: SfCalendar
documentation: ug
---
# Accessibility in Flutter Event Calendar (SfCalendar)
## Screen reader support
The `SfCalendar` can easily be accessed by screen readers. Please find the following table to get spoken feedback about the inner element contents of the screen.
### Month view
| View | Format | Example |
|-------------------|------------------------------|-----------------------------------------------|
| Month cell | EEE, dd/MMMM/yyyy | Thursday the 2nd of January 2020 |
| No events | EEE, dd/MMMM/yyyy, No events | Wednesday the 15th of January 2020, No events |
| No selected dates | No selected date | No selected date |
### TimeSlot view
| View | Format | Example |
|------------------------|--------------------------------------------|------------------------------------------------|
| Timeslot view | hh mm a dd/MMMM/yyyy | 11AM the 28th of January 2020 |
| All day expander icons | Expand all day panelCollapse all day panel | Expand all day sectionCollapse all day section |
| All day expander view | + appointment Count | +3 |
### Appointments
| View | Format | Example |
|-------------------------------|-----------------------------------------------------|------------------------------------------------------------------------------|
| Normal appointment | Subject hh mm a – hh mm a dd/MMMM/yyyy | Yoga therapy 10AM to 11AM the 29th of January 2020 |
| Month agenda view appointment | Subject hh mm a – hh mm a dd/MMMM/yyyy | Plan execution 9AM to 11AM the 23rd January 2020 |
| All day appointment | Subject All day | General meeting all day |
| Spanning appointment | Subject hh mm a dd/MMMM/yyyy - hh mm a dd/MMMM/yyyy | General meeting 12AM the 23rd of January 2020 – 1AM the 30th of January 2020 |
### Headers
| View | Format | Example |
|--------------------------|-------------------------|--------------------------------------|
| Header | MMMM yyyy | January 2020 |
| Timeline week header | dd/MMMM to dd/MMMM/yyyy | 15th of January to 21th January 2020 |
| Timeline workweek header | dd/MMMM to dd/MMMM/yyyy | 16th of January to 20th January 2020 |
| Month view header | EEE | Monday |
| TimeSlot view header | EEE, dd/MMMM/yyyy | Wednesday the 29th of January 2020 |
## Sufficient contrast
The `SfCalendar` [theming](https://help.syncfusion.com/flutter/themes) support offers a consistent and standardized look, as well as the ability to set the colors for all UI elements.
The following APIs allow you to customize the colors of the following elements.
* [todayHighlightColor](https://help.syncfusion.com/flutter/calendar/getting-started#today-highlight-color)
* [cellBorderColor](https://help.syncfusion.com/flutter/calendar/getting-started#cell-border-color)
* [backgroundColor](https://help.syncfusion.com/flutter/calendar/getting-started#background-color)
* [selectionDecoration](https://help.syncfusion.com/flutter/calendar/getting-started#selection-decoration)
* [agendasStyle](https://help.syncfusion.com/flutter/calendar/month-view#agenda-view-appearance)
* [monthCellStyle](https://help.syncfusion.com/flutter/calendar/month-view#month-cell-appearance)
* [dayHeaderSettings](https://help.syncfusion.com/flutter/calendar/schedule-view#day-header-customization)
* [weekHeaderSettings](https://help.syncfusion.com/flutter/calendar/schedule-view#week-header-customization)
* [monthHeaderSettings](https://help.syncfusion.com/flutter/calendar/schedule-view#month-header-customization)
* [resourceViewSettings](https://help.syncfusion.com/flutter/calendar/resource-view#customization)
## Large fonts
The `SfCalendar` font size can be adjusted automatically based on device settings and the font size scaled based on the `MediaQueryData.textScaleFactor`. And also it allows to change the font size of all UI elements in the calendar.
* [appointmentTextStyle](https://help.syncfusion.com/flutter/calendar/appointments#appearance-customization)
* [timeTextStyle](https://help.syncfusion.com/flutter/calendar/timeslot-views#time-text-appearance)
* [dateTextStyle](https://help.syncfusion.com/flutter/calendar/schedule-view#day-header-customization)
* [dayTextStyle](https://help.syncfusion.com/flutter/calendar/schedule-view#day-header-customization)
* [displayNameText style](https://help.syncfusion.com/flutter/calendar/resource-view#customization)
## Keyboard navigation
The following keyboard interactions are supported by the `SfCalendar`.
| Key | Description |
|------------------|-------------------------------------------------------------------------------------------|
| Up arrow | Moves selection to the next calendar cell directly above the currently selected time slot |
| Down arrow | Moves selection to the next calendar cell directly below the currently selected time slot |
| Right arrow | Moves selection to the same time slot on the next day |
| Left arrow | Moves selection to the same time slot on the previous day |
| Tab | Focuses the next clickable element, except appointments and cells |
| Shift + tab | Focuses the previous clickable element, except appointment and cells |

Просмотреть файл

@ -1,13 +1,13 @@
---
layout: post
title: Appointments in Flutter Event Calendar widget | Syncfusion | Scheduler
description: Learn here all about Appointments feature of Syncfusion Flutter Event Calendar (SfCalendar) widget and more.
title: Appointments | events in Syncfusion Flutter Calendar | Scheduler
description: Learn how to plan, configure and manage all day, recurrence and spanning appointments in Syncfusion Flutter Calendar.
platform: flutter
control: SfCalendar
documentation: ug
---
# Appointments in Flutter Event Calendar (SfCalendar)
# Appointments
SfCalendar widget has a built-in capability to handle the appointment arrangement internally based on the [CalendarDataSource](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/CalendarDataSource-class.html). [Appointment](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/Appointment-class.html) is a class, which holds the details about the appointment to be rendered in calendar.
@ -82,37 +82,37 @@ class MeetingDataSource extends CalendarDataSource {
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
String getStartTimeZone(int index) {
return appointments![index].startTimeZone;
return appointments[index].startTimeZone;
}
@override
String getEndTimeZone(int index) {
return appointments![index].endTimeZone;
return appointments[index].endTimeZone;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
}
@ -138,7 +138,7 @@ You can create a custom class `Meeting` with mandatory fields `from`, and `to`.
{% highlight Dart %}
class Meeting {
Meeting({this.eventName = '', required this.from, required this.to, required this.background, this.isAllDay = false});
Meeting({this.eventName, this.from, this.to, this.background, this.isAllDay});
String eventName;
DateTime from;
@ -162,37 +162,37 @@ class MeetingDataSource extends CalendarDataSource {
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
String getStartTimeZone(int index) {
return appointments![index].startTimeZone;
return appointments[index].startTimeZone;
}
@override
String getEndTimeZone(int index) {
return appointments![index].endTimeZone;
return appointments[index].endTimeZone;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
}
@ -297,11 +297,11 @@ The `recurrenceRule` is a string value (RRULE) that contains the details of the
| FREQ | Maintains the Repeat type value of the appointment. (Example: Daily, Weekly, Monthly, Yearly, Every week day) Example: FREQ=DAILY;INTERVAL=1 |
| INTERVAL | Maintains the interval value of the appointments. For example, when you create the daily appointment at an interval of 2, the appointments are rendered on the days Monday, Wednesday and Friday. (creates the appointment on all days by leaving the interval of one day gap) Example: FREQ=DAILY;INTERVAL=1 |
| COUNT | It holds the appointments count value. For example, when the recurrence appointment count value is 10, it means 10 appointments are created in the recurrence series. Example: FREQ=DAILY;INTERVAL=1;COUNT=10 |
| UNTIL | This property is used to store the recurrence end date value. For example, when you set the end date of appointment as 6/30/2020, the UNTIL property holds the end date value when the recurrence actually ends. Example: FREQ=DAILY;INTERVAL=1;UNTIL=20200827T183000Z |
| UNTIL | This property is used to store the recurrence end date value. For example, when you set the end date of appointment as 6/30/2020, the UNTIL property holds the end date value when the recurrence actually ends. Example: FREQ=DAILY;INTERVAL=1;UNTIL=8/25/2020 |
| BYDAY | It holds the “DAY” values of an appointment to render.For example, when you create the weekly appointment, select the day(s) from the day options (Monday/Tuesday/Wednesday/Thursday/Friday/Saturday/Sunday). When Monday is selected, the first two letters of the selected day “MO” is stored in the “BYDAY” property. When you select multiple days, the values are separated by commas. Example: FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE;COUNT=10 |
| BYMONTHDAY | This property is used to store the date value of the Month while creating the Month recurrence appointment. For example, when you create a Monthly recurrence appointment in the date 3, it means the BYMONTHDAY holds the value 3 and creates the appointment on 3rd day of every month. Example: FREQ=MONTHLY;BYMONTHDAY=3;INTERVAL=1;COUNT=10 |
| BYMONTH | This property is used to store the index value of the selected Month while creating the yearly appointments. For example, when you create the yearly appointment in the Month June, it means the index value for June month is 6 and it is stored in the BYMONTH field. The appointment is created on every 6th month of a year. Example: FREQ=YEARLY;BYMONTHDAY=16;BYMONTH=6;INTERVAL=1;COUNT=10 |
| BYSETPOS | This property is used to store the index value of the week. For example, when you create the monthly appointment in second week of the month, the index value of the second week (2) is stored in BYSETPOS. Example: FREQ=MONTHLY;BYDAY=MO;BYSETPOS=2;UNTIL=20200810T183000Z . If the property value is set to -1 and -2, the appointment will be added to the last week and second last week of the month.|
| BYSETPOS | This property is used to store the index value of the week. For example, when you create the monthly appointment in second week of the month, the index value of the second week (2) is stored in BYSETPOS. Example: FREQ=MONTHLY;BYDAY=MO;BYSETPOS=2;UNTIL=8/11/2020 |
### Adding recurrence appointment
@ -357,11 +357,11 @@ For creating custom recurrence appointment, you need to create a custom class `M
class Meeting {
Meeting(
{this.eventName = '',
required this.from,
required this.to,
required this.background,
this.isAllDay = false,
{this.eventName,
this.from,
this.to,
this.background,
this.isAllDay,
this.recurrenceRule});
String eventName;
@ -369,7 +369,7 @@ class Meeting {
DateTime to;
Color background;
bool isAllDay;
String? recurrenceRule;
String recurrenceRule;
}
{% endhighlight %}
@ -387,32 +387,32 @@ class MeetingDataSource extends CalendarDataSource {
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
@override
String getRecurrenceRule(int index) {
return appointments![index].recurrenceRule;
return appointments[index].recurrenceRule;
}
}
@ -457,41 +457,41 @@ class MeetingDataSource extends CalendarDataSource {
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
@override
String getRecurrenceRule(int index) {
return appointments![index].recurrenceRule;
return appointments[index].recurrenceRule;
}
}
class Meeting {
Meeting({this.eventName = '',
required this.from,
required this.to,
required this.background,
this.isAllDay = false,
Meeting({this.eventName,
this.from,
this.to,
this.background,
this.isAllDay,
this.recurrenceRule});
String eventName;
@ -499,7 +499,7 @@ class Meeting {
DateTime to;
Color background;
bool isAllDay;
String? recurrenceRule;
String recurrenceRule;
}
{% endhighlight %}
@ -659,47 +659,47 @@ class MeetingDataSource extends CalendarDataSource {
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
@override
String getRecurrenceRule(int index) {
return appointments![index].recurrenceRule;
return appointments[index].recurrenceRule;
}
@override
List<DateTime> getRecurrenceExceptionDates(int index) {
return appointments![index].exceptionDates;
return appointments[index].exceptionDates;
}
}
class Meeting {
Meeting(
{this.eventName = '',
required this.from,
required this.to,
required this.background,
this.isAllDay = false,
{this.eventName,
this.from,
this.to,
this.background,
this.isAllDay,
this.recurrenceRule,
this.exceptionDates});
@ -708,8 +708,8 @@ class Meeting {
DateTime to;
Color background;
bool isAllDay;
String? recurrenceRule;
List<DateTime>? exceptionDates;
String recurrenceRule;
List<DateTime> exceptionDates;
}
{% endhighlight %}
@ -747,92 +747,3 @@ Widget build(BuildContext context) {
{% endtabs %}
![Appearance customization](images/appointments/appearance-customization.png)
## Appointment time format
You can customize the displaying time format in the appointment widget in the month agenda view and schedule view of calendar by specifying the [appointmentTimeTextFormat](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/appointmentTimeTextFormat.html) property of the SfCalendar.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return SfCalendar(
view: CalendarView.month,
dataSource: _calendarDataSource,
appointmentTimeTextFormat: 'HH:mm',
monthViewSettings: MonthViewSettings(
showAgenda: true
),
);
}
{% endhighlight %}
{% endtabs %}
![Appointment time format](images/appointments/appointment_time_format.png)
## Appointment helper
### Get visible appointments
You can get the list of visible appointments by using the [getVisibleAppointments](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/CalendarDataSource/getVisibleAppointments.html) method available in the Calendar data source.
{% tabs %}
{% highlight Dart %}
@override
initState() {
_calendarController = CalendarController();
_dataSource = _getCalendarDataSource();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.month,
controller: _calendarController,
dataSource: _dataSource,
onViewChanged: (ViewChangedDetails details) {
List<DateTime> dates = details.visibleDates;
String calendarTimeZone = '';
List<Object> appointment = _dataSource.getVisibleAppointments(
dates[0], calendarTimeZone,
dates[(details.visibleDates.length) - 1]);
},
),
),
);
}
}
{% endhighlight %}
{% endtabs %}
>**NOTE**
* The `startTime` is required for the starting date from which to obtain the appointments.
## See also
* [How to design and configure your appointment editor in event calendar widget Flutter](https://www.syncfusion.com/kb/11204/how-to-design-and-configure-your-appointment-editor-in-event-calendar-widget-flutter)
* [How to get appointment details from the OnTap event of the Flutter event calendar](https://www.syncfusion.com/kb/10999/how-to-get-appointment-details-from-the-ontap-event-of-the-flutter-event-calendar)
* [How to style the appointment in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12162/how-to-style-the-appointment-in-the-flutter-event-calendar-sfcalendar)
* [How to exclude the dates from recurrence appointments in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12161/how-to-exclude-the-dates-from-recurrence-appointments-in-the-flutter-event-calendar)
* [How to add recurring appointments until the specified date in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12158/how-to-add-recurring-appointments-until-the-specified-date-in-the-flutter-event-calendar)
* [How to add the appointments to the Fire base database using appointment editor in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12110/how-to-add-the-appointments-to-the-firebase-database-using-appointment-editor-in-the)
* [How to work with the Fire base database and the Flutter event calendar (SfCalendar) for appointments](https://www.syncfusion.com/kb/12067/how-to-work-with-the-firebase-database-and-the-flutter-event-calendar-sfcalendar-for)
* [How to add google calendar events to the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12116/how-to-add-google-calendar-events-to-the-flutter-event-calendar-sfcalendar)
* [How to add additional attributes in events in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12209/how-to-add-additional-attributes-in-events-in-the-flutter-event-calendar-sfcalendar)
* [How to add the appointments using the onTap callback in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12300/how-to-add-the-appointments-using-the-ontap-callback-in-the-flutter-calendar)
* [How to set the arbitrary height to appointments in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12279/how-to-set-the-arbitrary-height-to-appointments-in-the-flutter-event-calendar-sfcalendar)
* [How to get the recurrence date collection in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12344/how-to-get-the-recurrence-date-collection-in-the-flutter-event-calendar-sfcalendar)
* [How to get the recurrence properties from RRULE in the Flutter calendar](https://www.syncfusion.com/kb/12370/how-to-get-the-recurrence-properties-from-rrule-in-the-flutter-calendar)
* [How to update blackout dates using onViewChanged callback in the Flutter calendar](https://www.syncfusion.com/kb/12368/how-to-update-blackout-dates-using-onviewchanged-callback-in-the-flutter-calendar)
* [How to use navigation drawer for view switching in the Flutter calendar](https://www.syncfusion.com/kb/12361/how-to-use-navigation-drawer-for-view-switching-in-the-flutter-calendar)
* [How to show the tapped appointment details on another page in the Flutter event calendar](https://www.syncfusion.com/kb/12358/how-to-show-the-tapped-appointment-details-on-another-page-in-the-flutter-event-calendar)
* [How to load appointments On-Demand in Flutter Calendar](https://www.syncfusion.com/kb/12658/how-to-load-appointments-on-demand-in-flutter-calendar)
* [How to load the google calendar events to the Flutter Calendar (SfCalendar) in iOS](https://www.syncfusion.com/kb/12647/how-to-load-the-google-calendar-events-to-the-flutter-calendar-sfcalendar-in-ios)
* [How to perform the CRUD operations in Flutter Calendar using Fire base database](https://www.syncfusion.com/kb/12623/how-to-perform-the-crud-operations-in-flutter-calendar-using-firebase-database)
* [How to add the appointments to Fire store Database using Flutter Calendar](https://www.syncfusion.com/kb/12616/how-to-add-the-appointments-to-firestore-database-using-flutter-calendar)
* [How to perform the CRUD operations in Flutter Calendar using Fire store database](https://www.syncfusion.com/kb/12661/how-to-perform-the-crud-operations-in-flutter-calendar-using-firestore-database)

Просмотреть файл

@ -1,327 +0,0 @@
---
layout: post
title: Builders in the Flutter Event Calendar widget | Syncfusion | Scheduler
description: Learn here all about builders feature of Syncfusion Flutter Event Calendar (SfCalendar) widget and more.
platform: flutter
control: SfCalendar
documentation: ug
---
# Builders in Flutter Event Calendar (SfCalendar)
The calendar allows you to create a responsive UI with conditions based on a widgets details, to design and create your custom view to the month cells and month header of schedule view in the calendar.
The calendar has two builders to create and assign your custom view:
* Month cell builder
* Schedule view month header builder
## Month cell builder
The [MonthCellBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/MonthCellBuilder.html) allows you to design your custom view and assign the view to the month cells of the calendar by returning an appropriate widget in the [monthCellBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/monthCellBuilder.html) of [SfCalendar](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar-class.html).
[MonthCellDetails](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/MonthCellDetails-class.html) - returns the details of the month cell.
`date` - returns the month cell date.
`appointments` - returns the month cell appointments.
`visibleDates` - returns the current view visible dates.
`bounds` - returns the month cell bounds.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.month,
monthCellBuilder:
(BuildContext buildContext, MonthCellDetails details) {
final Color backgroundColor =
_getMonthCellBackgroundColor(details.date);
final Color defaultColor =
Theme.of(context).brightness == Brightness.dark
? Colors.black54
: Colors.white;
return Container(
decoration: BoxDecoration(
color: backgroundColor,
border: Border.all(color: defaultColor, width: 0.5)),
child: Center(
child: Text(
details.date.day.toString(),
style: TextStyle(color: _getCellTextColor(backgroundColor)),
),
),
);
},
showDatePickerButton: true,
monthViewSettings: MonthViewSettings(
showTrailingAndLeadingDates: false,
)),
),
);
}
{% endhighlight %}
{% endtabs %}
![Month cell builder](images/builder/month_cell_builder.png)
## Schedule view month header builder
You can design your custom view and assign this view to the month header of a schedule view in the calendar by returning an appropriate widget using the [scheduleViewMonthHeaderBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/scheduleViewMonthHeaderBuilder.html) in the `SfCalendar`.
[ScheduleViewMonthHeaderDetails](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/ScheduleViewMonthHeaderDetails-class.html) - returns the required details of the schedule view month header.
`date` - returns the header date.
`bounds` - returns the header bounds.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.schedule,
dataSource: _calendarDataSource,
scheduleViewMonthHeaderBuilder: (BuildContext buildContext,
ScheduleViewMonthHeaderDetails details) {
final String monthName = _getMonthDate(details.date.month);
return Stack(
children: [
Image(
image: ExactAssetImage('images/' + monthName + '.png'),
fit: BoxFit.cover,
width: details.bounds.width,
height: details.bounds.height),
Positioned(
left: 55,
right: 0,
top: 20,
bottom: 0,
child: Text(
monthName + ' ' + details.date.year.toString(),
style: TextStyle(fontSize: 18),
),
)
],
);
},
showDatePickerButton: true),
),
);
}
{% endhighlight %}
{% endtabs %}
![Schedule view header builder](images/builder/schedule_view_month_header_builder.png)
## Appointment builder
The [CalendarAppointmentBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/CalendarAppointmentBuilder.html) allows you to design your custom view and assign the view to the appointment UI of the calendar by returning an appropriate widget in the [appointmentBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/appointmentBuilder.html) of `SfCalendar`.
[CalendarAppointmentDetails](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/CalendarAppointmentDetails-class.html): Returns the details of the appointment view.
`date`: The date associate with the appointment view.
`appointments`: List of appointments associated with the appointment view.
`bound`: Returns the appointment view bounds.
`isMoreAppointmentRegion`: Determines whether the widget replaces the more appointment region.
{% tabs %}
{% highlight Dart %}
class MyAppState extends State<MyApp> {
CalendarController _controller = CalendarController();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.day,
dataSource: _getCalendarDataSource(),
appointmentBuilder: (BuildContext context,
CalendarAppointmentDetails details) {
final Appointment meeting =
details.appointments.first;
final String image = _getImage();
if (_controller.view != CalendarView.month &&
_controller.view != CalendarView.schedule) {
return Container(
child: Column(
children: [
Container(
padding: EdgeInsets.all(3),
height: 50,
alignment: Alignment.topLeft,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(5),
topRight: Radius.circular(5)),
color: meeting.color,
),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
meeting.subject,
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
maxLines: 3,
softWrap: false,
overflow: TextOverflow.ellipsis,
),
!kIsWeb
? Container()
: Text(
'Time: ${DateFormat('hh:mm a').format(meeting.startTime)} - ' +
'${DateFormat('hh:mm a').format(meeting.endTime)}',
style: TextStyle(
color: Colors.white,
fontSize: 10,
),
)
],
)),
),
Container(
height: details.bounds.height - 70,
padding: EdgeInsets.fromLTRB(3, 5, 3, 2),
color: meeting.color.withOpacity(0.8),
alignment: Alignment.topLeft,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: Image(
image:
ExactAssetImage('images/' + image + '.png'),
fit: BoxFit.contain,
width: details.bounds.width,
height: 60)),
Text(
meeting.notes!,
style: TextStyle(
color: Colors.white,
fontSize: 10,
),
)
],
)),
),
Container(
height: 20,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(5),
bottomRight: Radius.circular(5)),
color: meeting.color,
),
),
],
),
);
}
return Container(
child: Text(meeting.subject),
);
},
)),
);
}
}
{% endhighlight %}
{% endtabs %}
![Appointment builder](images/builder/appointment-builder.png)
## Time region builder
The [TimeRegionBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/TimeRegionBuilder.html) allows you to design your custom view and assign the view to the time region view of the calendar by returning an appropriate widget in the [timeRegionBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/timeRegionBuilder.html) of SfCalendar.
[TimeRegionDetails](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/TimeRegionDetails-class.html): Returns the details of the time region view.
`date`: The date associate with the time region view.
`bound`: Returns the time region view bounds.
`region`: The Region detail associated with the time region view.
{% tabs %}
{% highlight Dart %}
List<TimeRegion> _getTimeRegions() {
final List<TimeRegion> regions = <TimeRegion>[];
DateTime date = DateTime.now();
date = DateTime(date.year, date.month, date.day, 12, 0, 0);
regions.add(TimeRegion(
startTime: date,
endTime: date.add(Duration(hours: 2)),
enablePointerInteraction: false,
color: Colors.grey.withOpacity(0.2),
text: 'Break'));
return regions;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.week,
specialRegions: _getTimeRegions(),
timeRegionBuilder:
(BuildContext context, TimeRegionDetails timeRegionDetails) {
if (timeRegionDetails.region.text == 'Lunch') {
return Container(
color: timeRegionDetails.region.color,
alignment: Alignment.center,
child: Icon(
Icons.restaurant,
color: Colors.grey.withOpacity(0.5),
),
);
} else if (timeRegionDetails.region.text == 'Not Available') {
return Container(
color: timeRegionDetails.region.color,
alignment: Alignment.center,
child: Icon(
Icons.block,
color: Colors.grey.withOpacity(0.5),
),
);
}
return Container(color: timeRegionDetails.region.color);
},
)),
);
}
{% endhighlight %}
{% endtabs %}
![Time regions builder](images/builder/timeregion-builder.png)
## See also
[How to customize the special time region using custom builder in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12192/how-to-customize-the-special-time-region-using-custom-builder-in-the-flutter-event-calendar)
[How to customize the appointments using custom builder in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12191/how-to-customize-the-appointments-using-custom-builder-in-the-flutter-event-calendar)
[How to customize the month cell based on the appointment using builder in the Flutter calendar (SfCalendar)](https://www.syncfusion.com/kb/12210/how-to-customize-the-month-cell-based-on-the-appointment-using-builder-in-the-flutter)
[How to customize the month cell with appointment count in the Flutter event Calendar (SfCalendar)](https://www.syncfusion.com/kb/12306/how-to-customize-the-month-cell-with-appointment-count-in-the-flutter-event-calendar)

Просмотреть файл

@ -1,37 +1,30 @@
---
layout: post
title: Getting started with Flutter Event Calendar widget | Syncfusion
description: Learn here about getting started with Syncfusion Event Calendar (SfCalendar) widget, its elements, and more.
title: Flutter calendar widget to schedule & manage events | Syncfusion
description: Getting started with the Syncfusion flutter calendar widget to schedule an event with seven built-in configurable views modes.
platform: flutter
control: SfCalendar
documentation: ug
---
# Getting started with Flutter Event Calendar (SfCalendar)
# Getting Started
This section explains the steps required to add the calendar widget and populate appointments to the calendar widget. This section covers only basic features needed to get started with Syncfusion calendar widget.
To get start quickly with our Flutter event calendar widget, you can check on this video.
<style>#flutterEventCalendarVideoTutorial{width : 90% !important; height: 300px !important }</style>
<iframe id='flutterEventCalendarVideoTutorial' src='https://www.youtube.com/embed/3OROjbAQS8Y'></iframe>
## Add Flutter calendar to an application
## Add flutter calendar to an application
Create a simple project using the instructions given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter calendar dependency to your pubspec.yaml file.
Add the Syncfusion flutter calendar dependency to your pubspec.yaml file.
{% highlight dart %}
dependencies:
syncfusion_flutter_calendar: ^xx.x.xx
syncfusion_flutter_calendar: ^17.4.39-beta
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of [`Syncfusion Flutter Calendar`](https://pub.dev/packages/syncfusion_flutter_calendar/versions) package.
**Get packages**
Run the following command to get the required packages.
@ -114,7 +107,7 @@ Widget build(BuildContext context) {
}
List<Meeting> _getDataSource() {
final List<Meeting> meetings = <Meeting>[];
meetings = <Meeting>[];
final DateTime today = DateTime.now();
final DateTime startTime =
DateTime(today.year, today.month, today.day, 9, 0, 0);
@ -124,35 +117,34 @@ List<Meeting> _getDataSource() {
return meetings;
}
class MeetingDataSource extends CalendarDataSource {
MeetingDataSource(List<Meeting> source) {
MeetingDataSource(List<Meeting> source){
appointments = source;
}
@override
DateTime getStartTime(int index) {
return appointments![index].from;
return appointments[index].from;
}
@override
DateTime getEndTime(int index) {
return appointments![index].to;
return appointments[index].to;
}
@override
String getSubject(int index) {
return appointments![index].eventName;
return appointments[index].eventName;
}
@override
Color getColor(int index) {
return appointments![index].background;
return appointments[index].background;
}
@override
bool isAllDay(int index) {
return appointments![index].isAllDay;
return appointments[index].isAllDay;
}
}
@ -353,108 +345,4 @@ Widget build(BuildContext context) {
![Background color](images/getting-started/calendar-background-color.png)
## Navigation arrow
Using the [showNavigationArrow](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/showNavigationArrow.html) property of the `SfCalendar`, you can navigate to the next or previous views of the calendar without swiping.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCalendar(
view: CalendarView.month,
showNavigationArrow: true,
),
);
}
{% endhighlight %}
{% endtabs %}
![Show Navigation Arrow](images/getting-started/show-navigation-arrow.jpg)
>**NOTE**
* The `showNavigationArrow` property is not applicable when the `view` is set to `CalendarView.schedule`.
## Cell end padding
You can customize the padding of appointment view end to make touch position for timeslot and month cell by using the [cellEndPadding](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/cellEndPadding.html) property in the calendar, which allows you to tap the calendar cell when the cell has appointments.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SfCalendar(
view: CalendarView.month,
cellEndPadding: 5,
dataSource: _getCalendarDataSource(),
monthViewSettings: MonthViewSettings(
appointmentDisplayMode:
MonthAppointmentDisplayMode.appointment),
)),
);
}
{% endhighlight %}
{% endtabs %}
![Cell end padding](images/getting-started/cell-end-padding.png)
## Current time indicator
You can display the current time indicator in all timeslot views of SfCalendar by using the [showCurrentTimeIndicator](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/showCurrentTimeIndicator.html) property and you can also customize the color of current time indicator by using the [todayHighlightColor](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/todayHighlightColor.html) property.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCalendar(
view: CalendarView.day,
showCurrentTimeIndicator: true,
),
);
}
{% endhighlight %}
{% endtabs %}
![showCurrentTimeIndicator](images/getting-started/current-time-indicator.png)
You can get the complete getting started sample from [here](https://github.com/SyncfusionExamples/flutter-calendar).
## See also
[How to switch between views of the event calendar in Flutter?](https://www.syncfusion.com/kb/10944/how-to-switch-between-views-of-the-event-calendar-in-flutter)
[How to update event calendar (SfCalendar) DisplayDate using showDatePicker in flutter](https://www.syncfusion.com/kb/11010/how-to-update-event-calendar-sfcalendar-displaydate-using-showdatepicker-in-flutter)
[How can we move to specific time while switching from month to day view in Flutter event calendar](https://www.syncfusion.com/kb/10943/how-can-we-move-to-specific-time-while-switching-from-month-to-day-view-in-flutter-event)
[How to customize the cell border in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12118/how-to-customize-the-cell-border-in-the-flutter-event-calendar-sfcalendar)
[How to apply theming in Flutter event calendar (SfCalendar)?](https://www.syncfusion.com/kb/11899/how-to-apply-theming-in-flutter-event-calendar-sfcalendar)
[How to add an image as background in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12243/how-to-add-an-image-as-background-in-the-flutter-event-calendar-sfcalendar)
[How to change the first day of week in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12222/how-to-change-the-first-day-of-week-in-the-flutter-event-calendar-sfcalendar)
[How to interact with event calendar cell when appointments loaded in the Flutter (SfCalendar)](https://www.syncfusion.com/kb/12218/how-to-interact-with-event-calendar-cell-when-appointments-loaded-in-the-flutter-sfcalendar)
[How to customize the selection using decoration in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12245/how-to-customize-the-selection-using-decoration-in-the-flutter-event-calendar-sfcalendar)
[How to navigate to the previous or next views using navigation arrows in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12247/how-to-navigate-to-the-previous-or-next-views-using-navigation-arrows-in-the-flutter-event)
[How to customize the current day color in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12336/how-to-customize-the-current-day-color-in-the-flutter-event-calendar-sfcalendar)
[How to show a particular week in a day view of Flutter event calendar(SfCalendar)](https://www.syncfusion.com/kb/12310/how-to-show-a-particular-week-in-a-day-view-of-flutter-event-calendarsfcalendar)
[How to customize the selection using decoration in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12245/how-to-customize-the-selection-using-decoration-in-the-flutter-event-calendar-sfcalendar)
[How to format the view header day and date in the Flutter event calendar (SfCalendar)](https://www.syncfusion.com/kb/12339/how-to-format-the-view-header-day-and-date-in-the-flutter-event-calendar-sfcalendar)

Просмотреть файл

@ -1,927 +0,0 @@
---
layout: post
title: Axis types in Flutter Cartesian Charts widget | Syncfusion
description: Learn here all about available Axis types of Syncfusion Flutter Cartesian Charts (SfCartesianChart) widget and more.
platform: flutter
control: Chart
documentation: ug
---
# Axis types in Flutter Cartesian Charts (SfCartesianChart)
Charts typically have two axes that are used to measure and categorize data: a vertical (Y) axis, and a horizontal (X) axis.
Vertical(Y) axis always uses numerical scale. Horizontal(X) axis supports the following types of scale:
* Category
* Numeric
* Date-time
* Date-time category
* Logarithmic
## Numeric axis
Numeric axis uses numerical scale and displays numbers as labels. By default, [`Numeric Axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis-class.html) is set to both horizontal axis and vertical axis.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: NumericAxis(),
primaryYAxis: NumericAxis()
)
)
)
);
}
{% endhighlight %}
![Numeric axis](images/axis-types/numeric.jpg)
### Inversed numeric axis
By using the [`isInversed`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/isInversed.html) property in Cartesian charts, the numeric axis can be inverted. Axis is rendered from the minimum value to the maximum value by default, and can be inverted from the maximum value to the minimum value.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: NumericAxis(isInversed: true),
primaryYAxis: NumericAxis(isInversed: true)
)
)
)
);
}
{% endhighlight %}
![Inversed Numeric axis](images/axis-types/inversed-numeric.png)
### Customizing range
To customize the range of an axis, use the [`minimum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/minimum.html) and [`maximum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/maximum.html) properties of [`NumericAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/NumericAxis.html). By default, nice range will be calculated automatically based on the provided data.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
minimum: 10,
maximum: 50
)
)
)
)
);
}
{% endhighlight %}
![Numeric axis range](images/axis-types/numeric_range.jpg)
### Customizing interval
Axis interval can be customized using the [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) property of [`ChartAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis-class.html). By default, nice interval will be calculated based on the minimum and maximum values of the provided data.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
// axis interval is set to 10
interval: 10
)
)
)
)
);
}
{% endhighlight %}
![Numeric axis interval](images/axis-types/numeric_interval.jpg)
### Applying padding to the range
Padding can be applied to the minimum and maximum extremes of the axis range using the [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property. Numeric axis supports the following types of padding:
* additional
* auto
* none
* normal
* round
**additional**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`additional`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), the axis range will be rounded and an interval of the axis will be added as padding to the minimum and maximum values of the range.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
// Additional range padding is applied to y axis
rangePadding: ChartRangePadding.additional
)
)
)
)
);
}
{% endhighlight %}
![RangePadding additional](images/axis-types/numeric_additional.jpg)
**auto**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`auto`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), the horizontal numeric axis takes none for padding calculation, whereas the vertical numeric axis takes normal for padding calculation. This is also the default value of rangePadding.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
rangePadding: ChartRangePadding.auto
)
)
)
)
);
}
{% endhighlight %}
![RangePadding auto](images/axis-types/numeric_auto.jpg)
**none**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`none`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), padding will not be applied to the axis.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
rangePadding: ChartRangePadding.none
)
)
)
)
);
}
{% endhighlight %}
**normal**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`normal`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), padding is applied to the axis based on the default range calculation.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
rangePadding: ChartRangePadding.normal
)
)
)
)
);
}
{% endhighlight %}
![RangePadding normal](images/axis-types/numeric_normal.jpg)
**round**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`round`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), axis range will be rounded to the nearest possible numeric value.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
rangePadding: ChartRangePadding.round
)
)
)
)
);
}
{% endhighlight %}
![RangePadding round](images/axis-types/numeric_round.jpg)
### Formatting the labels
The [`numberFormat`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/numberFormat.html) property of numeric axis formats the numeric axis labels with [`globalized label formats`](https://api.flutter.dev/flutter/intl/NumberFormat-class.html). The following code snippet demonstrates how to format numeric labels.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: NumericAxis(
// Y axis labels will be rendered with currency format
numberFormat: NumberFormat.simpleCurrency()
)
)
)
)
);
}
{% endhighlight %}
![Number format](images/axis-types/number_format.jpg)
Also refer [label format](./axis-customization#formatting-axis-label-content) and [date format](#formatting-the-labels-1) for formatting the labels
further.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting labels using the [`NumberFormat`](https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html) class and [`date Format`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
### Decimal places
The [`decimalPlaces`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/decimalPlaces.html) property of numeric axis can be used to control the number of decimal digits of the numeric axis labels. The default value of [`decimalPlaces`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/decimalPlaces.html) property is 3.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: NumericAxis(
deciamlPlaces: 5
),
primaryYAxis: NumericAxis(
decimalPlaces: 4,
rangPadding: ChartRangePadding.none
)
)
)
)
);
}
{% endhighlight %}
![Decimal Places](images/axis-types/numeric_decimalplaces.jpg)
N>
* In order to control the decimal places of the y-axis labels, you need to use [`decimalPlaces`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/decimalPlaces.html) property of the axis along with setting the [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) to [`none`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html).
* For x-axis labels, setting the [`decimalPlaces`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/decimalPlaces.html) alone is enough.
## Category axis
Category axis displays text labels instead of numbers. When the string values are bound to x values, then the x-axis must be initialized with CategoryAxis.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis()
)
)
)
);
}
{% endhighlight %}
![Category Axis](images/axis-types/category.jpg)
### Placing labels between the ticks
Labels in category axis can be placed on the ticks by setting the [`labelPlacement`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CategoryAxis/labelPlacement.html) to [`onTicks`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LabelPlacement-class.html). The default value of the [`labelPlacement`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CategoryAxis/labelPlacement.html) property is [`betweenTicks`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LabelPlacement-class.html). So, the labels will be placed between the ticks by default.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(
// Axis labels will be placed on the ticks
labelPlacement: LabelPlacement.onTicks
)
)
)
)
);
}
{% endhighlight %}
### Displaying labels after a fixed interval
To display the labels after a fixed interval n, set the [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) property of ChartAxis to n. The default value of interval is null.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(
labelPlacement: LabelPlacement.betweenTicks,
interval: 2
)
)
)
)
);
}
{% endhighlight %}
![Fixed interval](images/axis-types/category_interval.jpg)
### Indexed category axis
Category axis can also be rendered based on the index values of data source by setting the [`arrangeByIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CategoryAxis/arrangeByIndex.html) property to true in the axis.
{% highlight dart %}
final List<ChartData> chartData = [
ChartData('John', 10),
ChartData('David', 9),
ChartData('Brit', 10),
];
final List<ChartData> chartData2 = [
ChartData('Anto', 11),
ChartData('Peter', 12),
ChartData('Parker', 8),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(
// Axis will be rendered based on the index values
arrangeByIndex: true
),
series: <ChartSeries<ChartData, String>>[
ColumnSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData sales, _) => sales.x,
yValueMapper: (ChartData sales, _) => sales.y,
),
ColumnSeries<ChartData, String>(
dataSource: chartData2,
xValueMapper: (ChartData sales, _) => sales.x,
yValueMapper: (ChartData sales, _) => sales.y,
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
![Indexed category axis](images/axis-types/category_arrangebyIndex.jpg)
## Date-time axis
The date-time axis uses date-time scale and displays date-time values as axis labels in specified format.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis()
)
)
)
);
}
{% endhighlight %}
![DateTime axis](images/axis-types/datetime.jpg)
### Customizing range
To customize the range of an axis, use the [`minimum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/minimum.html) and [`maximum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/maximum.html) properties of [`DateTimeAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/DateTimeAxis.html). By default, nice range will be calculated automatically based on the provided data.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
minimum: DateTime(2010),
maximum: DateTime(2020)
)
)
)
)
);
}
{% endhighlight %}
![DateTime range](images/axis-types/datetime_range.jpg)
### Date-time intervals
The date-time intervals can be customized using the [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) and [`intervalType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/intervalType.html) properties of [`DateTimeAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/DateTimeAxis.html). For example, setting [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) as 2 and [`intervalType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/intervalType.html) to years, would consider 2 years to be an interval.
The Flutter Chart supports the following types of interval for date-time axis:
* auto
* years
* months
* days
* hours
* minutes
* seconds
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
// Interval type will be months
intervalType: DateTimeIntervalType.months,
interval: 2
)
)
)
)
);
}
{% endhighlight %}
![DateTime range](images/axis-types/datetime_interval.jpg)
#### See Also
* [Rendering flutter time series chart with hours interval](https://www.syncfusion.com/kb/12289/how-to-render-flutter-time-series-chart-using-the-charts-widget-sfcartesianchart).
### Double range support
Date-time axis [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) property can be customized using double value.
For example, if you are rendering a series with months in x-axis with an interval of 0.5, then the interval will be calculated in days. The interval calculation may vary depending upon the number of days in the month.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
interval: 0.5,
)
primaryXAxis: NumericAxis()
)
)
)
);
}
{% endhighlight %}
![doublerange](images/axis-types/doublerange.png)
### Applying padding to range
Padding can be applied to the [`minimum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/minimum.html) and [`maximum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/maximum.html) extremes of a range using the `RangePadding` property. The date-time axis supports the following types of padding:
* none
* round
* additional
* normal
**none**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`none`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), padding will not be applied to the axis.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
rangePadding: ChartRangePadding.none
)
)
)
)
);
}
{% endhighlight %}
![Range padding none](images/axis-types/datetime_rangePadding_none.jpg)
**round**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`round`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), axis range will be rounded to the nearest possible date-time value.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
rangePadding: ChartRangePadding.round
)
)
)
)
);
}
{% endhighlight %}
![RangePadding round](images/axis-types/datetime_rangePadding_round.jpg)
**additional**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`additional`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), range will be rounded and date-time interval of the axis will be added as padding to the minimum and maximum extremes of a range.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
rangePadding: ChartRangePadding.additional
)
)
)
)
);
}
{% endhighlight %}
![RangePadding round](images/axis-types/datetime_rangePadding_add.jpg)
**normal**
When the value of [`rangePadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/rangePadding.html) property is [`normal`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartRangePadding-class.html), padding will be applied to the axis based on the default range calculation.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
rangePadding: ChartRangePadding.normal
)
)
)
)
);
}
{% endhighlight %}
![RangePadding normal](images/axis-types/datetime_rangePadding_normal.jpg)
### Formatting the labels
The [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/dateFormat.html) property formats the date-time axis labels. The default data-time axis label can be formatted with various built-in [`date formats`](https://api.flutter.dev/flutter/intl/DateFormat-class.html), which depend on the given data source.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(
// X axis labels will be rendered based on the below format
dateFormat: DateFormat.y()
)
)
)
)
);
}
{% endhighlight %}
![Date format](images/axis-types/datetime_labelFormat.jpg)
Also refer [label format](./axis-customization#formatting-axis-label-content) and [number format](#formatting-the-labels) for formatting the labels further.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting labels using the [`NumberFormat`](https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html) class and [`date Format`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
## Date-time category axis
Date-time category axis is a combination of both [`DateTimeAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeAxis/DateTimeAxis.html) and [`CategoryAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CategoryAxis-class.html). Date-time category axis is used to display the date-time values with non-linear intervals. For example, the business days alone have been depicted in a week here.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeCategoryAxis()
)
)
)
);
}
{% endhighlight %}
![DateTimeCategory axis](images/axis-types/datetimecategory.jpg)
### Customizing range
To customize the range of an axis, use the [`minimum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis/minimum.html) and [`maximum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis/maximum.html) properties of [`DateTimeCategoryAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis-class.html). By default, nice range will be calculated automatically based on the provided data.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeCategoryAxis(
minimum: DateTime(2010, 2, 3),
maximum: DateTime(2010, 2, 10)
)
)
)
)
);
}
{% endhighlight %}
![DateTimeCategory range](images/axis-types/datetimecategory_range.jpg)
### Date-time intervals
The date-time category intervals can be customized using the [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) and [`intervalType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis/intervalType.html) properties of [`DateTimeCategoryAxis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis-class.html). For example, To display the axis labels after a fixed interval n, set the [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) property of ChartAxis to n and to display the labels in months, set the [`intervalType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis/intervalType.html) property of DateTimeCategoryAxis as months.
The Flutter Chart supports the following types of interval for date-time category axis:
* auto
* years
* months
* days
* hours
* minutes
* seconds
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeCategoryAxis(
// Interval type will be years
intervalType: DateTimeIntervalType.months,
interval: 2
)
)
)
)
);
}
{% endhighlight %}
![DateTimeCategory intervals](images/axis-types/datetimecategory_interval.jpg)
### Formatting the labels
The [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DateTimeCategoryAxis/dateFormat.html) property formats the date-time category axis labels. The default data-time category axis label can be formatted with various built-in [`date formats`](https://api.flutter.dev/flutter/intl/DateFormat-class.html), which depend on the given data source.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeCategoryAxis(
// X axis labels will be rendered based on the below format
dateFormat: DateFormat.yMMMd()
)
)
)
)
);
}
{% endhighlight %}
![DateTimeCategory date format](images/axis-types/datetimecategory_dateFormat.jpg)
Also refer [label format](./axis-customization#formatting-axis-label-content) and [number format](#formatting-the-labels) for formatting the labels further.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting labels using the [`NumberFormat`](https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html) class and [`date Format`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
## Logarithmic axis
Logarithmic axis uses logarithmic scale and displays numbers as axis labels.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: NumericAxis(),
primaryYAxis: LogarithmicAxis()
)
)
)
);
}
{% endhighlight %}
![Logarithmic axis](images/axis-types/logarthmic.jpg)
### Change logarithmic range
To customize the range of log axis, use the [`minimum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LogarithmicAxis/minimum.html), [`maximum`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LogarithmicAxis/maximum.html), and [`interval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/interval.html) properties. By default, the range will be calculated automatically based on the provided data.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: LogarithmicAxis(
minimum: 100,
maximum: 100000,
interval: 1,
)
)
)
)
);
}
{% endhighlight %}
![Logarithmic range](images/axis-types/logarthmic_range.jpg)
### Change log base value
To customize the log base value, use the [`logBase`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LogarithmicAxis/logBase.html) property.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryYAxis: LogarithmicAxis(
logBase: 5,
)
)
)
)
);
}
{% endhighlight %}
![Logarithmic base](images/axis-types/log_base.jpg)
### Inversed logarithmic axis
By using the [`isInversed`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/isInversed.html) Property in Cartesian charts, the logarithmic axis can be inverted. Axis gets rendered from the minimum value to the maximum value by default and can be inverted from the maximum value to the minimum value.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: LogarithmicAxis(
isInversed:true,
)
)
)
)
);
}
{% endhighlight %}
![Inversed logarithmic axis](images/axis-types/inversed-logarithmic.png)
## See Also
* [Applying currency format to axis labels](https://www.syncfusion.com/kb/11519/how-to-apply-the-currency-format-to-the-axis-labels-sfcartesianchart).

Просмотреть файл

@ -1,905 +0,0 @@
---
layout: post
title: Callbacks in Flutter Cartesian Charts widget | Syncfusion
description: Learn here all about available Callbacks feature of Syncfusion Flutter Cartesian Charts (SfCartesianChart) widget and more.
platform: flutter
control: Chart
documentation: ug
---
# Callbacks in Flutter Cartesian Charts (SfCartesianChart)
The below Callbacks are for Cartesian chart.
## onTooltipRender
Triggers when the tooltip is rendering. Here, you can customize the text, header, x and y-positions. The [`onTooltipRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onTooltipRender.html) Callback contains the following arguments.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/text.html) - specifies the content of the tooltip.
* [`header`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/header.html) - specifies the header content of the tooltip.
* [`locationX`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/locationX.html) - specifies the x position of tooltip.
* [`locationY`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/locationY.html) - specifies the y position of tooltip.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/seriesIndex.html) - specifies the current series index.
* [`dataPoints`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/dataPoints.html) - holds the data point collection.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/pointIndex.html) - specifies the current point index.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TooltipArgs/viewportPointIndex.html) - specifies the viewport index value of the tooltip.
{% highlight dart %}
late TooltipBehavior _tooltipBehavior;
@override
void initState(){
_tooltipBehavior = TooltipBehavior(enable: true);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
tooltipBehavior: _tooltipBehavior,
onTooltipRender: (TooltipArgs args) {
args.text = 'Customized Text';
}
)
)
);
}
{% endhighlight %}
## onActualRangeChanged
Triggers when the visible range of an axis is changed, i.e. value changes for minimum, maximum, and interval. Here, you can customize the visible range of an axis. The [`onActualRangeChanged`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onActualRangeChanged.html) Callback contains the following arguments.
* [`axisName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/axisName.html) - specifies the axis name.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/axis.html) - holds the information about the current axis.
* [`actualMin`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/actualMin.html) - specifies the actual minimum range of an axis.
* [`actualMax`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/actualMax.html) - specifies the actual maximum range of an axis.
* [`actualInterval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/actualInterval.html) - specifies the actual interval of an axis.
* [`visibleMin`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/visibleMin.html) - specifies the visible minimum range of an axis.
* [`visibleMax`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/visibleMax.html) - specifies the visible maximum range of an axis.
* [`visibleInterval`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/visibleInterval.html) - specifies the visible interval of an axis.
* [`orientation`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ActualRangeChangedArgs/orientation.html) - specifies the current axis orientation.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onActualRangeChanged: (ActualRangeChangedArgs args){
if (args.axisName == 'primaryYAxis'){
args.visibleMin = 10;
}
}
)
)
);
}
{% endhighlight %}
## onAxisLabelRender
Triggers while rendering the axis labels. Text and text styles such as color, font size, and font weight can be customized. The [`onAxisLabelRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onAxisLabelRender.html) Callback contains the following arguments.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/text.html) - specifies the axis label to be rendered.
* [`value`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/value.html) - specifies the actual value of the current axis label.
* [`axisName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/axisName.html) - specifies the axis name.
* [`orientation`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/orientation.html) - specifies the current axis orientation.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/axis.html) - holds the information about the current axis.
* [`textStyle`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelRenderArgs/textStyle.html) - used to change the text color, size, font family, font style, and font weight.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onAxisLabelRender: (AxisLabelRenderArgs args) {
if (args.axisName == 'primaryXAxis') {
args.text = 'Text';
TextStyle textStyle = args.textStyle;
args.textStyle = textStyle.copyWith(color: Colors.red);
}
}
)
)
);
}
{% endhighlight %}
#### See Also
* [Using dateTime values in y-axis using onAxisLabelRender callback](https://www.syncfusion.com/kb/12224/how-to-use-datetime-values-in-the-y-axis-sfcartesianchart).
## onDataLabelRender
Triggers when data label is rendering. Text and text styles such as color, font size, and font weight can be customized. The [`onDataLabelRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onDataLabelRender.html) Callback contains the following arguments.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/text.html) - used to get and set the content of the data label.
* [`textStyle`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/textStyle.html) - used to change the text color, size, font family, font style, and font weight.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/pointIndex.html) - specifies the current point index.
* [`seriesRenderer`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/seriesRenderer.html) - specifies current series and the series type may vary based on the chart type.
* [`dataPoints`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/dataPoints.html) - used to get the data points of the series.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/viewportPointIndex.html) - to get the viewport index value of the tapped data label.
* [`offset`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/offset.html) - used to get and set the horizontal/vertical position of the data label. The first argument sets the horizontal component to x, while the second argument sets the vertical component to y.
* [`color`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelRenderArgs/color.html) - used to get and set the background color of a data label.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onDataLabelRender:(DataLabelRenderArgs args){
args.text = 'Data label';
CartesianSeries<dynamic, dynamic> series = args.seriesRenderer;
//Changed the background color of the data label based on the series type
if (series.name == 'Product A') {
args.color = Colors.blue;
} else if(series.name == 'Product B'){
args.color = Colors.red;
}
},
series: <CartesianSeries>[
ColumnSeries<ChartData, double>(
dataLabelSettings: DataLabelSettings(
isVisible: true
)
)
]
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final double x;
final double? y;
}
{% endhighlight %}
## onLegendItemRender
Triggers when the legend item is rendering. Here, you can customize the legends text, and shape. The [`onLegendItemRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onLegendItemRender.html) Callback contains the following arguments.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendRenderArgs/text.html) - specifies the content of the legend.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendRenderArgs/pointIndex.html) - specifies the current point index that is applicable for circular chart type alone.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendRenderArgs/seriesIndex.html) - specifies the current series index.
* [`legendIconType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendRenderArgs/legendIconType.html) - specifies the shape of the legend.
* [`color`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendRenderArgs/color.html) - used to get and set the color of the legend icon.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
legend: Legend(isVisible: true),
onLegendItemRender: (LegendRenderArgs args){
args.text = 'Legend Text';
args.legendIconType = LegendIconType.diamond;
}
)
)
);
}
{% endhighlight %}
## onTrackballPositionChanging
Triggers while the trackball position is changing. Here, you can customize the text of the trackball.The [`onTrackballPositionChanging`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onTrackballPositionChanging.html) Callback contains the following argument.
* [`chartPointInfo`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrackballArgs/chartPointInfo.html) - holds the information about the current point.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onTrackballPositionChanging: (TrackballArgs args) {
args.chartPointInfo.label = 'Custom Text';
},
trackballBehavior: TrackballBehavior(
enable: true
)
)
)
);
}
{% endhighlight %}
## onCrosshairPositionChanging
Triggers while the crosshair position is changing. Here, you can customize the text and line color of the crosshair.The [`onCrosshairPositionChanging`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onCrosshairPositionChanging.html) Callback contains the following arguments.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/text.html) - used to get and set the crosshair tooltip content.
* [`value`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/value.html) - specifies the actual value of the crosshair.
* [`axisName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/axisName.html) - specifies the axis name.
* [`orientation`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/orientation.html) - specifies the current axis orientation.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/axis.html) - holds the information about the current axis.
* [`lineColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CrosshairRenderArgs/lineColor.html) - used to get and set the color of the crosshair line.
{% highlight dart %}
late CrosshairBehavior _crosshairBehavior;
@override
void initState(){
_crosshairBehavior = CrosshairBehavior(
enable: true
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onCrosshairPositionChanging: (CrosshairRenderArgs args){
args.text = 'crosshair';
},
crosshairBehavior: _crosshairBehavior
)
)
);
}
{% endhighlight %}
## onZooming
Triggers when the zooming action is in progress. The [`onZooming`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onZooming.html) Callback contains the following arguments.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/axis.html) - holds the information about the current axis.
* [`currentZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomPosition.html) - used to get and set the current zoom position of an axis.
* [`currentZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomFactor.html) - used to get and set the current zoom factor of an axis.
* [`previousZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomPosition.html) - specifies the previous zoom position of an axis.
* [`previousZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomFactor.html) - specifies the previous zoom factor of an axis.
{% highlight dart %}
late ZoomPanBehavior _zoomPanBehavior;
@override
void initState(){
_zoomPanBehavior = ZoomPanBehavior(
enableDoubleTapZooming: true,
enablePanning: true,
enablePinching: true,
enableSelectionZooming: true
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
zoomPanBehavior: _zoomPanBehavior,
onZooming: (ZoomPanArgs args){
print(args.currentZoomFactor);
print(args.currentZoomPosition);
}
)
)
);
}
{% endhighlight %}
## onZoomStart
Triggers when zooming action begins. The [`onZoomStart`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onZoomStart.html) Callback contains the following arguments.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/axis.html) - holds the information about the current axis.
* [`currentZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomPosition.html) - used to get and set the current zoom position of an axis.
* [`currentZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomFactor.html) - used to get and set the current zoom factor of an axis.
* [`previousZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomPosition.html) - specifies the previous zoom position of an axis.
* [`previousZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomFactor.html) - specifies the previous zoom factor of an axis.
{% highlight dart %}
late ZoomPanBehavior _zoomPanBehavior;
@override
void initState(){
_zoomPanBehavior = ZoomPanBehavior(
enableDoubleTapZooming: true,
enablePanning: true,
enablePinching: true,
enableSelectionZooming: true
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
zoomPanBehavior: _zoomPanBehavior,
onZoomStart: (ZoomPanArgs args){
print(args.currentZoomFactor);
print(args.currentZoomPosition);
}
)
)
);
}
{% endhighlight %}
## onZoomEnd
Triggers when the zooming action is completed. The [`onZoomEnd`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onZoomEnd.html) Callback contains the following arguments.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/axis.html) - holds the information about the current axis.
* [`currentZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomPosition.html) - used to get and set the current zoom position of an axis.
* [`currentZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomFactor.html) - used to get and set the current zoom factor of an axis.
* [`previousZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomPosition.html) - specifies the previous zoom position of an axis.
* [`previousZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomFactor.html) - specifies the previous zoom factor of an axis.
{% highlight dart %}
late ZoomPanBehavior _zoomPanBehavior;
@override
void initState(){
_zoomPanBehavior = ZoomPanBehavior(
enableDoubleTapZooming: true,
enablePanning: true,
enablePinching: true,
enableSelectionZooming: true
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
zoomPanBehavior: _zoomPanBehavior,
onZoomEnd: (ZoomPanArgs args){
print(args.currentZoomFactor);
print(args.currentZoomPosition);
}
)
)
);
}
{% endhighlight %}
## onZoomReset
Triggers when zoomed state is reset. The [`onZoomReset`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onZoomReset.html) Callback contains the following arguments.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/axis.html) - holds the information about the current axis.
* [`currentZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomPosition.html) - used to get and set the current zoom position of an axis.
* [`currentZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/currentZoomFactor.html) - used to get and set the current zoom factor of an axis.
* [`previousZoomPosition`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomPosition.html) - specifies the previous zoom position of an axis.
* [`previousZoomFactor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanArgs/previousZoomFactor.html) - specifies the previous zoom factor of an axis.
{% highlight dart %}
late ZoomPanBehavior _zoomPanBehavior;
@override
void initState(){
_zoomPanBehavior = ZoomPanBehavior(
enableDoubleTapZooming: true,
enablePanning: true,
enablePinching: true,
enableSelectionZooming: true
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
zoomPanBehavior: _zoomPanBehavior,
onZoomReset: (ZoomPanArgs args){
print(args.currentZoomFactor);
print(args.currentZoomPosition);
}
)
)
);
}
{% endhighlight %}
## onPointTapped
Triggers when tapping the series point. The [`onPointTapped`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onPointTapped.html) Callback contains the following arguments.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/PointTapArgs/seriesIndex.html) - specifies the current series index.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/PointTapArgs/pointIndex.html) - specifies the current point index.
* [`dataPoints`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/PointTapArgs/dataPoints.html) - holds the data point collection.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/PointTapArgs/viewportPointIndex.html) - specifies the viewport index value of the tapped data point.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onPointTapped: (PointTapArgs args){
print(args.seriesIndex);
print(args.pointIndex);
}
)
)
);
}
{% endhighlight %}
## onAxisLabelTapped
Triggers when tapping the axis label. The [`onAxisLabelTapped`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onAxisLabelTapped.html) Callback contains the following arguments.
* [`axis`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelTapArgs/axis.html) - holds the information about the current axis.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelTapArgs/text.html) - specifies the content of the axis label.
* [`value`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelTapArgs/value.html) - specifies the actual value of the current axis label.
* [`axisName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/AxisLabelTapArgs/axisName.html) - used to get the axis name.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onAxisLabelTapped: (AxisLabelTapArgs args) {
print(args.text);
}
)
)
);
}
{% endhighlight %}
#### See Also
* [Navigating to an hyperlink on axis label tap](https://www.syncfusion.com/kb/12202/how-to-navigate-to-a-hyperlink-when-clicked-on-chart-axis-label-sfcartesianchart).
## onLegendTapped
Triggers when tapping the legend item. The [`onLegendTapped`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onLegendTapped.html) Callback contains the following arguments.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendTapArgs/seriesIndex.html) - specifies the current series index.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendTapArgs/pointIndex.html) - specifies the current point index that is applicable for circular series.
* [`series`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendTapArgs/series.html) - specifies the current series and the series type may vary based on the chart type.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onLegendTapped: (LegendTapArgs args) {
print(args.seriesIndex);
},
legend: Legend(isVisible: true)
)
)
);
}
{% endhighlight %}
## onSelectionChanged
Triggers while selection changes. Here you can customize the selectedColor, unselectedColor, selectedBorderColor, selectedBorderWidth, unselectedBorderColor, and unselectedBorderWidth properties. The [`onSelectionChanged`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onSelectionChanged.html) Callback contains the following arguments.
* [`seriesRenderer`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/seriesRenderer.html) - specifies current series.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/seriesIndex.html) - specifies the current series index.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/pointIndex.html) - specifies the current point index.
* [`selectedColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/selectedColor.html) - used to get and set the color of the selected data points or series.
* [`unselectedColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/unselectedColor.html) - used to get and set the color of the unselected data points or series.
* [`selectedBorderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/selectedBorderColor.html) - used to get and set the border color of the selected data points or series.
* [`selectedBorderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/selectedBorderWidth.html) - used to get and set the border width of the selected data points or series.
* [`unselectedBorderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/unselectedBorderColor.html) - used to get and set the border color of the unselected data points or series.
* [`unselectedBorderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/unselectedBorderWidth.html) - used to get and set the border width of the unselected data points or series.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionArgs/viewportPointIndex.html) - used to get the viewport index value of the selected data points.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onSelectionChanged: (SelectionArgs args){
args.selectedColor = Colors.red;
args.unselectedColor = Colors.lightGreen;
},
series: <CartesianSeries>[
ColumnSeries<ChartData, double>(
selectionBehavior: SelectionBehavior(
enable: true,
)
)
]
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final double x;
final double? y;
}
{% endhighlight %}
## onIndicatorRender
Triggers when indicator is rendering. Here you can customize the name, signal line color, signal line width,dash array and so on.
The [`onIndicatorRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs-class.html) contains following arguments.
* [`indicatorName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/indicatorName.html) - used to get and set the indicator name.
* [`indicator`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/indicator.html) - used to get the technical indicator information.
* [`signalLineColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/signalLineColor.html) - used to change the color of the signal line.
* [`signalLineWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/signalLineWidth.html) - used to change the width of the signal line.
* [`lineDashArray`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/lineDashArray.html) - used to change the dash array size.
* [`seriesName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/seriesName.html) - specifies the series name.
* [`index`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/index.html) - specifies the current series index
* [`dataPoints`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/IndicatorRenderArgs/dataPoints.html) - specifies the current datapoints.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: SfCartesianChart(
onIndicatorRender: (IndicatorRenderArgs args)
{
if(args.index==0)
{
args.indicatorname='changed1';
args.signalLineColor=Colors.green;
args.signalLineWidth=6.0;
}
}
)
)
);
}
{% endhighlight %}
## onTrendlineRender
Triggers when the trendline gets rendered. Trendline properties like color,opacity can be customized using trendlineRender Callback. The [`onTrendlineRender`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs-class.html) Callback contains the following arguments.
* [`trendlineIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/trendlineIndex.html) - specifies the index of the trendline.
* [`opacity`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/opacity.html) - specifies the opacity of the trendline.
* [`seriesName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/seriesName.html) - specifies the series name of the trendline.
* [`color`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/color.html) - specifies the color of the trendline.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/seriesIndex.html) - specifies the seriesIndex.
* [`data`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/data.html) - specifies the data points of the series.
* [`trendlineName`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/trendlineName.html) - specifies the name of the trendline.
* [`intercept`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/intercept.html) - specifies the intercept value of the trendline.
* [`dashArray`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/TrendlineRenderArgs/dashArray.html) - specifies and sets the trendline's dashArray.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfCartesianChart(
onTrendlineRender: (TrendlineRenderArgs args) {
args.color = Colors.greenAccent;
args.opacity = 0.18;
args.dashArray = <double>[5, 3];
}
)
)
);
}
{% endhighlight %}
## onRendererCreated
Triggers when the series renderer is created. This callback can be used to obtain the [`ChartSeriesController`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeriesController-class.html) instance, which is used to access the the public methods in the series.
{% highlight dart %}
//Initialize the series controller
ChartSeriesController? _chartSeriesController;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
child: SfCartesianChart(
series: <LineSeries<SalesData, num>>[
LineSeries<SalesData, num>(
dataSource: chartData,
//Initialize the onRendererCreated event and store the controller for the respective series
onRendererCreated: (ChartSeriesController controller) {
_chartSeriesController = controller;
},
),
],
)
),
Container(
child: ElevatedButton(
onPressed: () {
//Removed a point from data source
chartData.removeAt(0);
//Added a point to the data source
chartData.add(ChartData(3,23));
//Here accessed the public method of the series.
_chartSeriesController?.updateDataSource(
addedDataIndexes: <int>[chartData.length -1],
removedDataIndexes: <int>[0],
);
},
child: Container(child: Text('Add a point'),)
)
)
]
);
}
class SalesData {
SalesData(this.x, this.y);
final num x;
final double? y;
}
{% endhighlight %}
## onChartTouchInteractionDown
Triggers when touched or clicked on the chart area. You can get the position of the touched region using this callback.
The callback contains the following argument:
* [`position`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartTouchInteractionArgs/position.html) - used to get the position of the touch interaction.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onChartTouchInteractionDown: (ChartTouchInteractionArgs args){
print(args.position.dx.toString());
print(args.position.dy.toString());
}
)
);
}
{% endhighlight %}
## onChartTouchInteractionUp
Triggers when tapped or clicked on the chart area. You can get the position of the tapped region using this callback.
The callback contains the following argument:
* [`position`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartTouchInteractionArgs/position.html) - used to get the position of the touch interaction.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onChartTouchInteractionUp: (ChartTouchInteractionArgs args){
print(args.position.dx.toString());
print(args.position.dy.toString());
}
)
);
}
{% endhighlight %}
## onChartTouchInteractionMove
Triggers when touched or clicked and moved on the chart area. You can get the position of the moving region using this callback.
The callback contains the following argument:
* [`position`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartTouchInteractionArgs/position.html) - used to get the position of the touch interaction.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onChartTouchInteractionMove: (ChartTouchInteractionArgs args){
print(args.position.dx.toString());
print(args.position.dy.toString());
}
)
);
}
{% endhighlight %}
## onMarkerRender
Triggers when the marker is being rendered. Here, you can customize the following arguments.
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/pointIndex.html) - to get the point index of the marker.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/seriesIndex.html) - to get the series index of the marker.
* [`shape`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/shape.html) - to get and set the shape of the marker.
* [`markerHeight`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/markerHeight.html) - to get and set the height of the marker.
* [`markerWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/markerWidth.html) - to get and set the width of the marker.
* [`color`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/color.html) - to get and set the color of the marker.
* [`borderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/borderWidth.html) - to get and set the border width of the marker.
* [`borderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/borderColor.html) - to get and set the border color of the marker.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/MarkerRenderArgs/viewportPointIndex.html) - to get the viewport index value of the tapped data label.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onMarkerRender: (MarkerRenderArgs args) {
if (args.pointIndex == 1) {
args.color = Colors.red;
args.markerHeight = 20;
args.markerWidth = 20;
args.shape = DataMarkerType.diamond;
args.borderColor = Colors.green;
args.borderWidth = 2;
}
},
)
);
}
{% endhighlight %}
## onDataLabelTapped
Triggers when tapping on the data label of the data point in the series. The [`onDataLabelTapped`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onDataLabelTapped.html) Callback contains the following arguments.
* [`position`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/position.html) - specifies the position of the tapped data label in logical pixels.
* [`seriesIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/seriesIndex.html) - specifies the series index of the tapped data label
* [`pointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/pointIndex.html) - specifies the point index of the tapped data label.
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/text.html) - specifies the content of the tapped data label.
* [`dataLabelSettings`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/dataLabelSettings.html) - to get the data label customization options specified in that particular series.
* [`viewportPointIndex`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelTapDetails/viewportPointIndex.html) - to get the viewport index value of the tapped data label.
N> This callback will not be called, when the builder is specified for data label (data label template). For this case, custom widget specified in the [`DataLabelSettings.builder`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/DataLabelSettings/builder.html) property can be wrapped using the [`GestureDetector`](https://api.flutter.dev/flutter/widgets/GestureDetector-class.html) and this functionality can be achieved in the application level.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onDatalabelTapped: (DataLabelTapArgs args) {
print(args.seriesIndex);
},
series: <ChartSeries<Sample, DateTime>>[
LineSeries<Sample, DateTime>(
dataSource: chartData,
xValueMapper: (Sample sales, _) => sales.x,
yValueMapper: (Sample sales, _) => sales.y,
dataLabelSettings: DataLabelSettings(
isVisible: true),
)
]
)
);
}
class Sample{
Sample(this.x, this,y);
final DateTime x;
final double? y;
}
{% endhighlight %}
## onPlotAreaSwipe
Triggers while swiping on the plot area. Whenever the swiping happens on the plot area (the series rendering area), [`onPlotAreaSwipe`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/onPlotAreaSwipe.html) callback will be called. It provides options to get the direction of swiping. If the chart is swiped from left to right direction, the direction is [`ChartSwipeDirection.start`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSwipeDirection-class.html) and if the swipe happens from right to left direction, the direction is [`ChartSwipeDirection.end`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSwipeDirection-class.html). Using this callback, the user will be able to achieve pagination functionality (i.e., on swiping over chart area, next set of data points can be loaded to the chart).
{% highlight dart %}
//Initialize the series controller
ChartSeriesController? SeriesController;
@override
Widget build(BuildContext context) {
return Container(
child: SfCartesianChart(
onPlotAreaSwipe:
(ChartSwipeDirection direction) =>
performSwipe(direction),
series: <ChartSeries<SalesData, num>>[
AreaSeries<SalesData, num>(
dataSource: chartData,
),
],
)
);
}
Widget performSwipe(ChartSwipeDirection direction) {
if (direction == ChartSwipeDirection.end) {
chartData.add(ChartSampleData(
x: chartData[chartData.length - 1].x + 1,
y: 10));
seriesController?.updateDataSource(addedDataIndex: chartData.length - 1);
}
}
class SalesData {
SalesData(this.x, this.y);
final num x;
final double? y;
}
{% endhighlight %}
## See Also
* [Customize the tooltip using its callback event](https://www.syncfusion.com/kb/11507/how-to-customize-the-tooltip-using-callback-events-sfcartesianchart).
* [Customize the axis labels using its callback event](https://www.syncfusion.com/kb/11678/how-to-customize-the-axis-labels-using-callback-events-sfcartesianchart).
* [Customize the data labels using its callback event](https://www.syncfusion.com/kb/11679/how-to-customize-data-labels-using-callback-events-sfcartesianchart).
* [Disabling trackball tooltip for particular series using its callback event](https://www.syncfusion.com/kb/11638/how-to-disable-trackball-tooltip-for-particular-series-in-cartesian-charts-sfcartesianchart).
* [To Synchronize panning in multiple charts](https://www.syncfusion.com/kb/11533/how-to-synchronize-panning-in-multiple-charts-sfcartesianchart).
N> `chartData` in the above code snippets is a class type list and holds the data for binding to the chart series. Refer [Bind data source](https://help.syncfusion.com/flutter/cartesian-charts/getting-started#bind-data-source) topic for more details.

Просмотреть файл

@ -1,423 +0,0 @@
---
layout: post
title: Legend in Flutter Cartesian Charts widget | Syncfusion
description: Learn here all about Legend feature of Syncfusion Flutter Cartesian Charts (SfCartesianChart) widget and more.
platform: flutter
control: Chart
documentation: ug
---
# Legend in Flutter Cartesian Charts (SfCartesianChart)
The [`legend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/legend.html) contains list of chart series/data points in chart. The information provided in each legend item helps to identify the corresponding data series in chart.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child:SfCartesianChart(
primaryXAxis: DateTimeAxis(),
// Enables the legend
legend: Legend(isVisible: true),
series: <LineSeries>[
LineSeries<ChartData, DateTime>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final DateTime x;
final double? y;
}
{% endhighlight %}
![Legend](images/legend/legend.png)
## Customizing legend
The [`name`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/name.html) property of [`CartesianSeries`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries-class.html) is used to define the label for the corresponding series legend item .The appearance of the label can be customized using the below properties.
* [`borderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/borderWidth.html) - used to change the stroke width of the legend shape.
* [`borderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/borderColor.html) - used to change the stroke color of the legend shape.
* [`backgroundColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/backgroundColor.html) - used to change the background color of legend shape.
* [`opacity`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/opacity.html) - used to control the transparency of the legend icon shape.
* [`padding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/padding.html) - used to add padding between the icon shape and the text.
* [`iconHeight`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/iconHeight.html) - used to change the height of the icon shape.
* [`iconWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/iconWidth.html) - used to change the width of the icon shape.
* [`borderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/borderWidth.html) - used to change the stroke width of the legend icon shape.
* [`iconBorderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/iconBorderColor.html) - used to change the stroke color of the legend icon shape.
* [`itemPadding`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/itemPadding.html) - used to add padding between the first legend text and the second legend icon shape.
* [`height`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/height.html) - the height of the legend.
* [`width`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/width.html) - the width of the legend.
* [`isResponsive`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/isResponsive.html) - toggles the visibility of the legend. If the width or height of the legend is greater than the plot area bounds.
* [`iconBorderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/iconBorderWidth.html) - border width of the icon in the legend items. Used to change the stroke width of the legend icon shape.
* [`overflowMode`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/overflowMode.html) - overflow legend items.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child:SfCartesianChart(
primaryXAxis: DateTimeAxis(),
legend: Legend(
isVisible: true,
name:legend,
// Border color and border width of legend
borderColor: Colors.black,
borderWidth: 2
),
series: <CartesianSeries>[
LineSeries<ChartData, DateTime>(
name:'line-series',
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final DateTime x;
final double? y;
}
{% endhighlight %}
![Customized Legend](images/legend/customized_legend.png)
## Legend title
The following properties can be used to define and customize the [`title`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/title.html) of [`legend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/legend.html).
* [`text`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendTitle/text.html) - used to change the text of the title.
* [`textStyle`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the text color, size, font family, fontStyle, and font weight.
* [`textStyle.color`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the color of the text.
* [`textStyle.fontFamily`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the font family for legend text.
* [`textStyle.fontStyle`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the font style for the legend text.
* [`textStyle.fontSize`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the font size for the legend text.
* [`alignment`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/textStyle.html) - used to change the alignment of the title text, it can be near, center, or far.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child:SfCartesianChart(
primaryXAxis: DateTimeAxis(),
legend: Legend(
isVisible: true,
// Legend title
title: LegendTitle(
text:'Country',
textStyle: TextStyle(
color: Colors.red,
fontSize: 15,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w900
)
),
),
series: <CartesianSeries>[
LineSeries<ChartData, DateTime>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
),
LineSeries<ChartData, DateTime>(
dataSource: chartData1,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final DateTime x;
final double? y;
}
{% endhighlight %}
![Legend title](images/legend/legend_tittle.png)
## Toggles the series visibility
You can control the visibility of the series by tapping the legend item. You can enable this feature by enabling the [`toggleSeriesVisibility`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/toggleSeriesVisibility.html) property.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child:SfCartesianChart(
primaryXAxis: CategoryAxis(),
legend: Legend(
isVisible: true,
// Toogles the series visibility on tapping the legend item
toggleSeriesVisibility: true
),
series: <CartesianSeries>[
LineeSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
## Legend visibility
The [`isVisible`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/isVisible.html) property of [`legend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/legend.html) is used to toggle the visibility of legend.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child:SfCartesianChart(
primaryXAxis: CategoryAxis(),
legend: Legend(
// Visibility of legend
isVisible: false
),
series: <CartesianSeries>[
LineSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
## Legend item visibility
You can control the visibility of a particular series legend item using the [`isVisibleInLegend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/isVisibleInLegend.html) property of series. The default value of the [`isVisibleInLegend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/isVisibleInLegend.html) property is true. If it is set to false, then the legend item for this specific series will not be displayed in the legend.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
legend: Legend(
isVisible: true
),
primaryXAxis: CategoryAxis(),
series: <ColumnSeries>[
ColumnSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
),
ColumnSeries<ChartData, String>(
// Hiding the legend item for this series
isVisibleInLegend: false,
dataSource: chartData1,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
![Legend isVisibleInLegend](images/legend/toggle_visibility.jpg)
## Legend overflow
The legend items can be placed in multiple rows or scroll can be enabled using the [`overflowMode`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/overflowMode.html) property if size of the total legend items exceeds the available size. The default value of the [`overflowMode`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/overflowMode.html) property is [`scroll`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendItemOverflowMode-class.html).
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(),
legend: Legend(
isVisible: true,
// Overflowing legend content will be wraped
overflowMode: LegendItemOverflowMode.wrap
),
series: <CartesianSeries>[
LineSeries<ChartData, DateTime>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final DateTime x;
final double? y;
}
{% endhighlight %}
![Legend](images/legend/overflow_wrap.png)
## Positioning the legend
You can change the position of the legend inside the chart. The following properties can be used to customize the position of legend. auto position will place the legend at the right, if the chart's width is greater than the chart's height. Else the legend will be placed at the bottom position.
* [`position`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendPosition-class.html) - used to position the legend relatively. The available options are auto, bottom, left, right, and top. Defaults to `auto`.
* [`orientation`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/orientation.html) - used to change the orientation of the legend, the default value is auto. Also you can set [`horizontal`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendItemOrientation-class.html) or [`vertical`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/LegendItemOrientation-class.html).
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(),
legend: Legend(
isVisible: true,
// Legend will be placed at the left
position: LegendPosition.left
),
series: <CartesianSeries>[
AreaSeries<ChartData, DateTime>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
),
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final DateTime x;
final double? y;
}
{% endhighlight %}
![Legend](images/legend/legend_position.png)
## Legend item template
You can customize the appearance of legend items with your template by using [`legendItemBuilder`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/legendItemBuilder.html) property of [`legend`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/legend.html). Here you can specify the content that needs to be displayed in the legend text as widget.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(),
legend: Legend(
isVisible: true,
// Templating the legend item
legendItemBuilder: (String name, dynamic series, dynamic point, int index) {
return Container(
child: Container(
child: Text('template'))
);
}
),
series: <CartesianSeries>[
AreaSeries<ChartData, String>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
N> `chartData` in the above code snippets is a class type list and holds the data for binding to the chart series. Refer [Bind data source](https://help.syncfusion.com/flutter/cartesian-charts/getting-started#bind-data-source) topic for more details.

Просмотреть файл

@ -1,222 +0,0 @@
---
layout: post
title: Selection in Flutter Cartesian Charts widget | Syncfusion
description: Learn here all about Selection feature of Syncfusion Flutter Cartesian Charts (SfCartesianChart) widget and more.
platform: flutter
control: Chart
documentation: ug
---
# Selection in Flutter Cartesian Charts (SfCartesianChart)
The selection feature in chart let you to select a segment in a series or the series itself. This features allows you to select either individual or cluster of segments in the chart series.
{% highlight dart %}
late SelectionBehavior _selectionBehavior;
@override
void initState(){
_selectionBehavior = SelectionBehavior(
// Enables the selection
enable: true);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
series: <CartesianSeries>[
ColumnSeries<ChartData, double>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y,
selectionBehavior: _selectionBehavior
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final double x;
final double? y;
}
{% endhighlight %}
## Customizing the segments
You can customize the segments using the below properties.
* [`selectedColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/selectedColor.html) - used to change the background color of selected segment.
* [`unselectedColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/unselectedColor.html) - used to change the background color of unselected segment.
* [`selectedBorderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/selectedBorderColor.html) - used to change the stroke color of the selected segment.
* [`selectedBorderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/selectedBorderWidth.html) - used to change the stroke width of the selected segment.
* [`unselectedBorderColor`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/unselectedBorderColor.html) - used to change the stroke color of the unselected segment.
* [`unselectedBorderWidth`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/unselectedBorderWidth.html) - used to change the stroke width of the unselected segment.
* [`selectedOpacity`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/selectedOpacity.html) - used to control the transparency of the selected segment.
* [`unselectedOpacity`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/unselectedOpacity.html) - used to control the transparency of the unselected segment.
* [`selectionController`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionBehavior/selectionController.html) - to customize the minimum range of selected series or points.
{% highlight dart %}
late SelectionBehavior _selectionBehavior;
@override
void initState(){
_selectionBehavior = SelectionBehavior(
enable: true,
selectedColor: Colors.red,
unselectedColor: Colors.grey);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(),
series: <CartesianSeries>[
ColumnSeries<ChartData, String>(
selectionBehavior: _selectionBehavior
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
![Customizing segments](images/selection/customizing_segments.jpg)
## Selection modes
The selection features allows you to select segments in following modes using [`selectionType`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/selectionType.html) property of chart.
* [`Point`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionType-class.html) - selects the individual data point.
* [`Series`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionType-class.html) - selects the entire series.
* [`Cluster`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SelectionType-class.html) - selects the cluster of points of different series i.e selects the points with same index in each series.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
// Mode of selection
selectionType: SelectionType.cluster
)
)
)
);
}
{% endhighlight %}
![Cluster mode](images/selection/cluster_mode.jpg)
## Multi-selection
Multiple selection can be enabled using the [`enableMultiSelection`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/enableMultiSelection.html) property of chart.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
// Enables multiple selection
enableMultiSelection: true
)
)
)
);
}
{% endhighlight %}
![Multi selection](images/selection/multi_select.jpg)
## Selection on initial rendering
You can select a point or series programmatically on a chart using [`initialSelectedDataIndexes`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/initialSelectedDataIndexes.html) property of chart.
{% highlight dart %}
late SelectionBehavior _selectionBehavior;
@override
void initState(){
_selectionBehavior = SelectionBehavior(
// Enables the selection
enable: true );
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(),
series: <CartesianSeries>[
ColumnSeries<ChartData, String>(
// Initially selected the data at point index - 1.
initialSelectedDataIndexes: <int>[1],
dataSource: chartData1,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y,
selectionBehavior: _selectionBehavior
),
ColumnSeries<ChartData, String>(
dataSource: chartData2,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y,
selectionBehavior: _selectionBehavior
)
]
)
)
)
);
}
class ChartData {
ChartData(this.x, this.y);
final String x;
final double? y;
}
{% endhighlight %}
![Initial selection](images/selection/initial_render_selection.jpg)
Also refer [selection event](./events#onselectionchanged) for customizing the selection further.
#### See Also
* [Dynamically selecting the data points in a chart](https://www.syncfusion.com/kb/11811/how-to-select-the-data-points-dynamically-in-cartesian-charts-sfcartesianchart).
N> `chartData` in the above code snippets is a class type list and holds the data for binding to the chart series. Refer [Bind data source](https://help.syncfusion.com/flutter/cartesian-charts/getting-started#bind-data-source) topic for more details.

Просмотреть файл

@ -1,174 +0,0 @@
---
layout: post
title: Accessibility in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about the accessibility of the Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Accessibility in Flutter DataGrid (SfDataGrid)
## Screen reader support
The `SfDataGrid` can be accessed easily by the screen readers in the following ways in Android and iOS platforms:
* Cell contents can be read by tapping the required cell.
* Read the adjacent cell's content by swiping right or left.
* Scroll the datagrid vertically and horizontally by dragging two fingers.
## Sufficient contrast
The `SfDataGrid` provides the sufficient color contrast to make the cell content easier. Use the following properties to customize the appearance of the datagrid elements.
* [currentCellStyle](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/currentCellStyle.html)
* [frozenPaneElevation](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/frozenPaneElevation.html)
* [frozenPaneLineColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/frozenPaneLineColor.html)
* [gridLineColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/gridLineColor.html)
* [headerColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/headerColor.html)
* [headerHoverColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/headerHoverColor.html)
* [selectionColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/selectionColor.html)
* [sortIconColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/sortIconColor.html)
## Large fonts
As `SfDataGrid` gets the widget from user end for each cell, the font size in that widget will be automatically changed based on OS settings in Android and iOS platforms. To clearly view the cell content, the row heights in the datagrid will be automatically adjusted based on `MediaQueryData.textScaleFactor`.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return MediaQuery(
data: MediaQueryData(textScaleFactor: 1.5),
child: SfDataGrid(
source: employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
visible: false,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Keyboard navigation
The `SfDataGrid` provides the keyboard navigation support when the [selectionMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/selectionMode.html) and [navigationMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/navigationMode.html) are enabled. Refer this [link](https://help.syncfusion.com/flutter/datagrid/selection#keyboard-behavior) for supported keys and their purpose.
## Visual density
The row heights in `SfDataGrid` will be automatically adjusted based on the [visualDensity](https://api.flutter.dev/flutter/material/ThemeData/visualDensity.html).
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(visualDensity: VisualDensity.compact),
child: SfDataGrid(
source: employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
visible: false,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,290 +0,0 @@
---
layout: post
title: Column in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to add columns to Syncfusion Flutter DataGrid (SfDataGrid) control and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Column Types in Flutter DataGrid (SfDataGrid)
[SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) provides support for load any type of widget in each column.
The following table describes the types of columns and its usage:
| Column Type | Renderer | Description |
|-----------------------|---------------------------------|----------------------------------------|
| GridTextColumn | GridCellTextFieldRenderer | Use to display the String data |
## GridColumn
GridColumn is a class that provides base functionalities for all the column types in `SfDataGrid`.
### Mapping column to a property
Column can be bound to a property in data object using [GridColumn.columnName](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/mappingName.html) property. [label](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/headerText.html) is used to display the required widget in a column header.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
### Hiding a column
[GridColumn.visible](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/visible.html) property can be used to set a column as hidden. The default value of the `visible` property is true.
>**NOTE**
Set the `visible` property to `false` instead of setting column width as `0` to hide a column.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
visible: false,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
### Set manual width for column
`SfDataGrid` allows you to customize the width of each [GridColumn](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn-class.html) in the [SfDataGrid.Columns](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/columns.html) collection. To customize column width, use the [GridColumn.width](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/width.html) property. By default, this property will not be assigned any value. The GridColumn renders in view based on the value of the [defaultColumnWidth](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/defaultColumnWidth.html) property.
>**NOTE**
Set the `visible` property to `false` instead of setting column width as `0` to hide a column.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
width: 100.0,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## GridTextColumn
[GridTextColumn](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridTextColumn-class.html) inherits all the properties of GridColumn.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,289 +0,0 @@
---
layout: post
title: Columns sizing in Flutter DataGrid | Syncfusion | DataTable
description: Learn here all about how to set the width for columns in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Column sizing in Flutter DataGrid (SfDataGrid)
[SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) allows to set the column widths based on certain logic using [SfDataGrid.columnWidthMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/columnWidthMode.html) or [GridColumn.columnWidthMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/columnWidthMode.html) property. Below are the list of predefined column sizing options available.
| Mode | Description |
|---------------------------|-----------------------------------------------------|
| ColumnWidthMode.lastColumnFill | Applies default Column width to all the columns except last column which is visible and the remaining width from total width of SfDataGrid is set to last column. |
| ColumnWidthMode.fill | Divides the total width equally for columns. |
| ColumnWidthMode.none | No sizing. Default column width or defined width set to column. |
> **NOTE**
[ColumnWidthMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/ColumnWidthMode-class.html) will not work when the column width defined explicitly. `columnWidthMode` calculates column width based on miniumWidth and maximumWidth properties.
The following example shows how to set the width equally for column based on the view port size.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'city',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
> **NOTE**
The `GridColumn.columnWidthMode` takes higher priority than the `SfDataGrid.columnWidthMode`.
![columns filled based on view port size in flutter datagrid](images/autofit-columns/flutter-datagrid-fill-columns.png)
## Fill remaining width for any column
While setting `SfDataGrid.columnWidthMode` as `lastColumnFill` remaining width is applied to last column. The remaining width to specific column can be applied by setting `GridColumn.columnWidthMode` property.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columnWidthMode: ColumnWidthMode.lastColumnFill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![The last column is filled in view in flutter datagrid](images/autofit-columns/flutter-datagrid-fill-lastcolumn.png)
The below example shows Name column is set as `lastColumnFill` mode.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
columnWidthMode: ColumnWidthMode.lastColumnFill,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![Name column is filled with remaining available space in flutter datagrid](images/autofit-columns/flutter-datagrid-fill-anycolumn.png)
## Recalculating column widths when datasource is changed
By default, column widths are calculated based on the `columnWidthMode` property on initial loading of datagrid. When the datasource is changed for same datagrid at run time, datagrid does not recalculate the column widths. To recalculate the column widths at run time when datasource is changed or data is updated, you can override the [shouldRecalculateColumnWidths](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/shouldRecalculateColumnWidths.html) method and return `true`.
Returning true may impact performance as the column widths are recalculated again (whenever the notifyListeners is called). If you are aware that column widths are going to be same whenever underlying data changes, return `false` from this method.
{% tabs %}
{% highlight Dart %}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
bool shouldRecalculateColumnWidths() {
return true;
}
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,347 +0,0 @@
---
layout: post
title: Conditional Styling in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to style the rows and columns in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Conditional Styling in Flutter DataGrid (SfDataGrid)
The [SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) allows to customize the style of the individual cells and rows based on the requirements. You can customize your widget in the `DataGridSource.buildRow` method with the help of `DataGridRowAdapter`.
## Cells
### Styling based on content
The appearance of the cells in `SfDataGrid` can be customized conditionally based on the content and set your widget to the `DataGridRowAdapter.cells`.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columnWidthMode: ColumnWidthMode.lastColumnFill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
Color getColor() {
if (dataGridCell.columnName == 'designation') {
if (dataGridCell.value == 'Developer') {
return Colors.tealAccent;
} else if (dataGridCell.value == 'Manager') {
return Colors.blue[200]!;
}
}
return Colors.transparent;
}
TextStyle? getTextStyle() {
if (dataGridCell.columnName == 'designation') {
if (dataGridCell.value == 'Developer') {
return TextStyle(fontStyle: FontStyle.italic);
} else if (dataGridCell.value == 'Manager') {
return TextStyle(fontStyle: FontStyle.italic);
}
}
return null;
}
return Container(
color: getColor(),
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
style: getTextStyle(),
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows conditional formatting in cells](images/conditional-styling/flutter-datagrid-cells-styling-based-on-content.png)
### Styling alternate cells
The appearance of the alternating cells in a column can be customized conditionally by using the `DataGridSource.buildRow` method.
{% tabs %}
{% highlight Dart %}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
if (dataGridCell.columnName == 'id') {
final int index = dataGridRows.indexOf(row);
return Container(
color: (index % 2 != 0) ? Colors.blueAccent : Colors.transparent,
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
style: (index % 2 != 0)
? TextStyle(fontStyle: FontStyle.italic)
: null,
));
}
return Container(
alignment: (dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows alternate cells styling](images/conditional-styling/flutter-datagrid-alternate-cells-styling.png)
## Rows
### Styling based on content
The appearance of the rows in `SfDataGrid` can be customized conditionally based on the content in `DataGridRowAdapter.color`.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter buildRow(DataGridRow row) {
Color getRowBackgroundColor() {
final int salary = row.getCells()[3].value;
if (salary >= 10000 && salary < 15000) {
return Colors.blue[300]!;
} else if (salary <= 15000) {
return Colors.orange[300]!;
}
return Colors.transparent;
}
TextStyle? getTextStyle() {
final int salary = row.getCells()[3].value;
if (salary >= 10000 && salary < 15000) {
return TextStyle(color: Colors.white);
} else if (salary <= 15000) {
return TextStyle(color: Colors.white);
}
return null;
}
return DataGridRowAdapter(
color: getRowBackgroundColor(),
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
style: getTextStyle(),
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows styling a row based on content](images/conditional-styling/flutter-datagrid-rows-styling-based-on-content.png)
### Styling alternate rows
The appearance of the alternating rows in `SfDataGrid` can be customized by using the `DataGridRowAdapter.color`.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
Color getRowBackgroundColor() {
final int index = dataGridRows.indexOf(row);
if (index % 2 != 0) {
return Colors.lightGreen[300]!;
}
return Colors.transparent;
}
return DataGridRowAdapter(
color: getRowBackgroundColor(),
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows styling alternate rows](images/conditional-styling/flutter-datagrid-alternate-rows-styling.png)

Просмотреть файл

@ -1,411 +0,0 @@
---
layout: post
title: Data Binding in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to set datasource for Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Data Binding in Flutter DataGrid (SfDataGrid)
[SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) requires the [DataGridSource](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource-class.html) to obtain the row data. In order to bind data source of the SfDataGrid, set an instance of the `DataGridSource` to the [source](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/source.html) property.`source` property must not be null.
The following APIs in the `DataGridSource` are mandatory to process the data,
* [rows](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/rows.html) - The number of rows in a datagrid and row selection depends on the `rows`. So, set the `DataGridRow` collection required for datagrid in
`rows`.
* [buildRow](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/buildRow.html) - The widget needed for the cells is obtained from `DataGridRowAdapter`.
`DataGridSource` objects are expected to be long-lived, not recreated with each build.
The following example shows how to create the `DataGridSource`,
{% tabs %}
{% highlight dart %}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
The following example shows how to set the `source` property in `SfDataGrid`
{% tabs %}
{% highlight dart %}
late EmployeeDataSource _employeeDataSource;
List<Employee> _employees = <Employee>[];
@override
void initState() {
super.initState();
_employees = getEmployeeData();
employeeDataSource = EmployeeDataSource(employees: _employees);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columnWidthMode: ColumnWidthMode.lastColumnFill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Data manipulation in Flutter DataGrid (SfDataGrid)
`SfDataGrid` provides support to update or refresh the DataGrid when an underlying data is updated i.e. CRUD operation is performed in an underlying data.
If row is added, removed or replaced in an underlying datasource, you can call the [notifyListeners](https://api.flutter.dev/flutter/foundation/ChangeNotifier/notifyListeners.html).
In the following example, row is added and `notifyListeners` is called in `onPressed` callback of the `TextButton`. As the `notifyListeners` is the protected method, we have introduced the `updateDataGridSource` method in EmployeeDataSource class and called the `notifyListeners` method. So, users can call `updateDataGridSource` methods in widget level to refresh the datagrid.
N> `notifyListeners` should be called from inside the `DataGridSource`.
{% tabs %}
{% highlight Dart %}
final List<Employee> _employees = <Employee>[];
final EmployeeDataSource _employeeDataSource = EmployeeDataSource();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
FlatButton(
child: const Text('Add row'),
onPressed: () {
_employees
.add(Employee(10011, 'Steve', 'Designer', 15000));
_employeeDataSource.buildDataGridRows();
_employeeDataSource.updateDataGridSource();
}),
SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
],
),
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource() {
buildDataGridRows();
}
void buildDataGridRows() {
dataGridRows = _employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
void updateDataGridSource() {
notifyListeners();
}
}
{% endhighlight %}
{% endtabs %}
If the value of the specific cell is updated, you can `notifyDataSourceListeners` method with [RowColumnIndex](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/RowColumnIndex-class.html) argument where it refers the corresponding row and column index of the cell.
So, DataGrid refreshes the corresponding cell alone.
In the following example, cell value is updated and `notifyDataSourceListeners` is called in `onPressed` callback of the `TextButton`.
{% tabs %}
{% highlight Dart %}
final List<Employee> _employees = <Employee>[];
final EmployeeDataSource _employeeDataSource = EmployeeDataSource();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter DataGrid'),
),
body: Column(
children: [
FlatButton(
child: const Text('Update cell value'),
onPressed: () {
_employees[0].salary = 25000;
_employeeDataSource.dataGridRows[0] = DataGridRow(cells: [
DataGridCell(value: employees[0].id, columnName: 'id'),
DataGridCell(value: employees[0].name, columnName: 'name'),
DataGridCell(
value: employees[0].designation,
columnName: 'designation'),
DataGridCell(
value: employees[0].salary, columnName: 'salary'),
]);
_employeeDataSource.updateDataGridSource(
rowColumnIndex: RowColumnIndex(0, 3));
}),
SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
],
),
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource() {
buildDataGridRows();
}
void buildDataGridRows() {
dataGridRows = _employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
void updateDataGridSource({RowColumnIndex rowColumnIndex}) {
notifyDataSourceListeners(rowColumnIndex: rowColumnIndex);
}
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,863 +0,0 @@
---
layout: post
title: Freeze panes in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about freeze Panes (fixed headers) feature of Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Freeze Panes in Flutter DataGrid (SfDataGrid)
The rows and columns can freeze in view like Excel. The rows and columns can be freeze by setting following properties,
<table>
<tr>
<th> Property Name </th>
<th> Description </th>
</tr>
<tr>
<td>
frozenRowsCount
</td>
<td>
Set the frozen rows count at top of the <code>SfDataGrid</code>.
</td>
</tr>
<tr>
<td>
footerFrozenRowsCount
</td>
<td>
Set the footer rows count at bottom of the <code>SfDataGrid</code>.
</td>
</tr>
<tr>
<td>
frozenColumnsCount
</td>
<td>
Set the frozen columns count in left side of the <code>SfDataGrid</code>.
</td>
</tr>
<tr>
<td>
footerFrozenColumnsCount
</td>
<td>
Set the footer columns in right side of the <code>SfDataGrid</code>.
</td>
</tr>
</table>
## Freeze columns
The columns can be frozen in view at left and right like Excel by setting the [frozenColumnsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/frozenColumnsCount.html) and [footerFrozenColumnsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/footerFrozenColumnsCount.html) properties.
The following code example shows how to freeze a column at left using `frozenColumnsCount`,
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
frozenColumnsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows frozen column at left](images/frozen-pane/flutter-datagrid-frozen-column.gif)
The following code example shows how to freeze a column at right using `footerFrozenColumnsCount`,
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
footerFrozenColumnsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows frozen column at right](images/frozen-pane/flutter-datagrid-footer-frozen-column.png)
### Limitation
* `frozenColumnsCount` or `footerFrozenColumnsCount` should be lesser than number of columns displayed in the view. For example, If you have 5 columns in view, then you can set `frozenColumnsCount` to a maximum value of 4.
## Freeze rows
The rows can be frozen in view at top and bottom like Excel by setting the [frozenRowsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/frozenRowsCount.html) and [footerFrozenRowsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/footerFrozenRowsCount.html) properties.
The following code example shows how to freeze a row at top using `frozenRowsCount`,
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
frozenRowsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows frozen row at top](images/frozen-pane/flutter-datagrid-frozen-row.gif)
The following code example shows how to freeze a row at bottom using `footerFrozenRowsCount`,
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
footerFrozenRowsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows frozen row at bottom](images/frozen-pane/flutter-datagrid-footer-frozen-row.png)
### Limitation
* `frozenRowsCount` or `footerFrozenRowsCount` should be lesser than the number of rows displayed in the view. For example, If you have 10 rows in view, then you set `frozenRowsCount` to a maximum value of 9.
N> Header row is frozen by default and works regardless of the `frozenRowsCount` property.
## Appearance
`SfDataGrid` allows to customize the appearance of the freeze pane through [SfDataGridTheme.SfDataGridThemeData](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData-class.html) property. The frozen line will be shown only the [SfDataGridThemeData.frozenPaneElevation](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/frozenPaneElevation.html) property to 0.
The freeze pane line and freeze pane width can be changed by [frozenPaneLineColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/frozenPaneLineColor.html) and [frozenPaneLineWidth](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/frozenPaneLineWidth.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGridTheme(
data: SfDataGridThemeData(
frozenPaneElevation: 0.0,
frozenPaneLineColor: Colors.red,
frozenPaneLineWidth: 1.5),
child: SfDataGrid(
source: _orderDataGridSource,
frozenRowsCount: 1,
footerFrozenRowsCount: 1,
frozenColumnsCount: 1,
footerFrozenColumnsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
)),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows freeze pane customization](images/frozen-pane/flutter-datagrid-frozen-pane-customization.png)
`SfDataGrid` allows to customize the appearance of the freeze pane elevation by using the `SfDataGridThemeData.frozenPaneElevation`. The default value of frozenPaneElevation is 5.0.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGridTheme(
data: SfDataGridThemeData(frozenPaneElevation: 7.0),
child: SfDataGrid(
source: _orderDataGridSource,
frozenRowsCount: 1,
frozenColumnsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
)),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customization of freeze pane elevation](images/frozen-pane/flutter-datagrid-customized-frozen-elevation.png)
## Hide freeze pane elevation
By default, elevation effect is applied to frozen panes. If you want to hide the freeze pane elevation and show only the frozen pane line, you can simply set `SfDataGridThemeData.frozenPaneElevation` property to 0. You can customize the appearance of frozen line by using `SfDataGridThemeData.frozenPaneLineColor` and `SfDataGridThemeData.frozenPaneLineWidth` properties.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGridTheme(
data: SfDataGridThemeData(
frozenPaneElevation: 0.0,
frozenPaneLineColor: Colors.red,
frozenPaneLineWidth: 1.5),
child: SfDataGrid(
source: _orderDataGridSource,
frozenRowsCount: 1,
frozenColumnsCount: 1,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Product ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'quantity',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Quantity',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'unitPrice',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Unit Price',
overflow: TextOverflow.ellipsis,
),
),
),
],
)),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows how to hide the frozen pane elevation](images/frozen-pane/flutter-datagrid-hide-frozen-elevation.png)

Просмотреть файл

@ -1,436 +0,0 @@
---
layout: post
title: Getting started with Flutter DataGrid | DataTable | Syncfusion
description: Learn here about getting started with Syncfusion Flutter DataGrid (SfDataGrid) widget, its basic features, and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Getting started with Flutter DataGrid (SfDataGrid)
This section explains the steps required to add the DataGrid widget and its features. This section covers only basic features needed to get started with the Syncfusion Flutter DataGrid widget.
To get start quickly with Flutter DataGrid, you can check on this video:
<style>#FlutterDataGridVideoTutorial{width : 90% !important; height: 400px !important }</style>
<iframe id='FlutterDataGridVideoTutorial' src='https://www.youtube.com/embed/-ULsEfjxFuY'></iframe>
## Add Flutter DataGrid to an application
Create a simple project using the instruction given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter DataGrid dependency to your pubspec.yaml file.
{% highlight dart %}
dependencies:
syncfusion_flutter_datagrid: ^xx.x.xx
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of [`Syncfusion Flutter DataGrid`](https://pub.dev/packages/syncfusion_flutter_datagrid/versions) package.
**Get packages**
Run the following command to get the required packages.
{% highlight dart %}
$ flutter pub get
{% endhighlight %}
**Import package**
Import the following package in your Dart code.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
{% endhighlight %}
{% endtabs %}
## Initialize DataGrid
Add the SfDataGrid widget as a child of any widget. [SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) requires the [source](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/source.html) and [columns](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/columns.html) properties. You can find the more details on these properties in further topics.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Creating Data for an application
The `SfDataGrid` is depending upon the data. Create a simple datasource for `SfDataGrid` as shown in the following code example.
{% tabs %}
{% highlight Dart %}
class Employee {
Employee(this.id, this.name, this.designation, this.salary);
final int id;
final String name;
final String designation;
final int salary;
}
{% endhighlight %}
{% endtabs %}
Create the collection of Employee data with the required number of data objects. Here, the `getEmployeeData` method which is used to populate the data objects is initialized in `initState()`.
{% tabs %}
{% highlight Dart %}
late EmployeeDataSource _employeeDataSource;
List<Employee> _employees = <Employee>[];
@override
void initState() {
super.initState();
_employees = getEmployeeData();
employeeDataSource = EmployeeDataSource(employees: _employees);
}
List<Employee> getEmployeeData() {
return [
Employee(10001, 'James', 'Project Lead', 20000),
Employee(10002, 'Kathryn', 'Manager', 30000),
Employee(10003, 'Lara', 'Developer', 15000),
Employee(10004, 'Michael', 'Designer', 15000),
Employee(10005, 'Martin', 'Developer', 15000),
Employee(10006, 'Newberry', 'Developer', 15000),
Employee(10007, 'Balnc', 'Developer', 15000),
Employee(10008, 'Perry', 'Developer', 15000),
Employee(10009, 'Gable', 'Developer', 15000),
Employee(10010, 'Grimes', 'Developer', 15000)
];
}
{% endhighlight %}
{% endtabs %}
## Creating DataSource for DataGrid
[DataGridSource](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource-class.html) is used to obtain the row data for the `SfDataGrid`. So, create the DataSource from the DataGridSource and override the following APIs in it,
* **`rows`** - Fetches the rows available for data population. Also, it is used to fetch the corresponding data object to process the selection. This contains the collection of `DataGridRow` where each row contains the collection of `DataGridCell`. Each cell should have the cell value in `value` property. `value` is used to perform the sorting for columns.
* **`buildRow`** - Fetches the widget for each cell with `DataGridRowAdapter`.
`DataGridSource` objects are expected to be long-lived, not recreated with each build.
{% tabs %}
{% highlight Dart %}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource(List<Employee> employees) {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
}
{% endhighlight %}
{% endtabs %}
Create an instance of `DataGridSource` and set this object to `source` property of `SfDataGrid`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
));
}
{% endhighlight %}
{% endtabs %}
## Defining columns
`SfDataGrid` supports to add any widget in a column using the [GridTextColumn] property. You can add the column collection to the `columns` property.
{% tabs %}
{% highlight Dart %}
late EmployeeDataSource _employeeDataSource;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows different column types](images/getting-started/getting-started-flutter-datagrid.png)
## Selection
`SfDataGrid` allows you to select one or more rows. The [selectionMode](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/selectionMode.html) property can be set to specify whether a user can select single row, or multiple rows.
{% tabs %}
{% highlight Dart %}
late EmployeeDataSource _employeeDataSource;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
selectionMode: SelectionMode.multiple,
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows rows with selection](images/getting-started/flutter-datagrid-selection.png)
The information about the rows that are selected can be retrieved using [selectedIndex](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController/selectedIndex.html), [selectedRow](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController/selectedRow.html) and [selectedRows](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController/selectedRows.html) properties in [DataGridController](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController-class.html). You need to initialize the `DataGridController` object to the [controller](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/controller.html) property of `SfDataGrid`.
`DataGridController` objects are expected to be long-lived, not recreated with each build.
{% tabs %}
{% highlight Dart %}
late EmployeeDataSource _employeeDataSource;
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
RaisedButton(
child: Text('Get Selection Information'),
onPressed: () {
int selectedIndex = _controller.selectedIndex;
DataGridRow selectedRow = _controller.selectedRow;
List<DataGridRow> selectedRows = _controller.selectedRows;
print(selectedIndex);
print(selectedRow);
print(selectedRows);
}),
Expanded(
child: SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
selectionMode: SelectionMode.multiple,
),
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
>**NOTE**
`SfDataGrid` supports selection via keyboard interaction for the Web and Desktop platform when `selectionMode` is not `none`.

Просмотреть файл

@ -1,437 +0,0 @@
---
layout: post
title: Load More in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to perform lazy loading of rows in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Load more in Flutter Datagrid (SfDataGrid)
The datagrid provides support to display an interactive view when the grid reaches its maximum offset while scrolling down. You can use [loadMoreViewBuilder](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/loadMoreViewBuilder.html) builder to display the view at bottom of datagrid.
You should override the [DataGridSource.handleLoadMoreRows](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/handleLoadMoreRows.html) method to load more rows and then notify the datagrid about the changes. The `DataGridSource.handleLoadMoreRows` can be called to load more rows from this builder by using the [loadMoreRows](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/LoadMoreRows.html) function which is passed as a parameter to `loadMoreViewBuilder`.
## Infinite scrolling
Infinite Scrolling is an approach that can be used to load more rows to the datagrid whenever the datagrid reaches the bottom.
The following example demonstrates infinite scrolling by showing the circular progress indicator until the rows are loaded when the datagrid reaches the bottom,
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
source: employeeDataSource,
loadMoreViewBuilder: (BuildContext context, LoadMoreRows loadMoreRows) {
Future<String> loadRows() async {
// Call the loadMoreRows function to call the
// DataGridSource.handleLoadMoreRows method. So, additional
// rows can be added from handleLoadMoreRows method.
await loadMoreRows();
return Future<String>.value('Completed');
}
return FutureBuilder<String>(
initialData: 'loading',
future: loadRows(),
builder: (context, snapShot) {
if (snapShot.data == 'loading') {
return Container(
height: 60.0,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
border: BorderDirectional(
top: BorderSide(
width: 1.0,
color: Color.fromRGBO(0, 0, 0, 0.26)))),
alignment: Alignment.center,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.deepPurple)));
} else {
return SizedBox.fromSize(size: Size.zero);
}
},
);
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource() {
buildDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
Future<void> handleLoadMoreRows() async {
await Future.delayed(Duration(seconds: 5));
_addMoreRows(_employees, 15);
buildDataGridRows();
notifyListeners();
}
void buildDataGridRows() {
dataGridRows = _employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
void _addMoreRows(List<Employee> employees, int count) {
final Random _random = Random();
final startIndex = employees.isNotEmpty ? employees.length : 0,
endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
employees.add(Employee(
1000 + i,
_names[_random.nextInt(_names.length - 1)],
_designation[_random.nextInt(_designation.length - 1)],
10000 + _random.nextInt(10000),
));
}
}
final List<String> _names = <String>[
'Welli',
'Blonp',
'Folko',
'Furip',
'Folig',
'Picco',
'Frans',
'Warth',
'Linod',
'Simop',
'Merep',
'Riscu',
'Seves',
'Vaffe',
'Alfki'
];
final List<String> _designation = <String>[
'Project Lead',
'Developer',
'Manager',
'Designer',
'System Analyst',
'CEO'
];
}
{% endhighlight %}
{% endtabs %}
**NOTE**
Download demo application from [GitHub](https://github.com/SyncfusionExamples/how-to-do-the-infinite-scrolling-in-syncfusion-flutter-datatable).
![flutter datagrid shows load more with infinite scrolling behavior](images/load-more/flutter-datagrid-load-more-infinite-scrolling.gif)
## Load more button
Showing load more button is an approach that can be used to load more rows to the datagrid by tapping a button that you load from the `SfDataGrid.loadMoreViewBuilder` builder. The button will be loaded when vertical scrolling is reached at the end of the datagrid.
The following example demonstrates how to show the button when vertical scrolling is reached at the end of the datagrid and display the circular indicator until the rows are loaded when you tap that button. In the onPressed flat button callback, you can call the `loadMoreRows` function to add more rows,
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
source: employeeDataSource,
loadMoreViewBuilder: (BuildContext context, LoadMoreRows loadMoreRows) {
bool showIndicator = false;
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
if (showIndicator) {
return Container(
height: 60.0,
width: double.infinity,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
border: BorderDirectional(
top: BorderSide(
width: 1.0, color: Color.fromRGBO(0, 0, 0, 0.26)))),
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.deepPurple)));
} else {
return Container(
height: 60.0,
width: double.infinity,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.white,
border: BorderDirectional(
top: BorderSide(
width: 1.0, color: Color.fromRGBO(0, 0, 0, 0.26)))),
child: Container(
height: 36.0,
width: 142.0,
child: FlatButton(
color: Colors.deepPurple,
child:
Text('LOAD MORE', style: TextStyle(color: Colors.white)),
onPressed: () async {
// To avoid the "Error: setState() called after dispose():"
// while scrolling the datagrid vertically and displaying the
// load more view, current load more view is checked whether
// loaded widget is mounted or not.
if (context is StatefulElement &&
context.state != null &&
context.state.mounted) {
setState(() {
showIndicator = true;
});
}
// Call the loadMoreRows function to call the
// DataGridSource.handleLoadMoreRows method. So, additional
// rows can be added from handleLoadMoreRows method.
await loadMoreRows();
// To avoid the "Error: setState() called after dispose():"
// while scrolling the datagrid vertically and displaying the
// load more view, current load more view is checked whether
// loaded widget is mounted or not.
if (context is StatefulElement &&
context.state != null &&
context.state.mounted) {
setState(() {
showIndicator = false;
});
}
},
),
),
);
}
});
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource() {
buildDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
Future<void> handleLoadMoreRows() async {
await Future.delayed(Duration(seconds: 5));
_addMoreRows(_employees, 15);
buildDataGridRows();
notifyListeners();
}
void buildDataGridRows() {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
void _addMoreRows(List<Employee> employees, int count) {
final Random _random = Random();
final startIndex = employees.isNotEmpty ? employees.length : 0,
endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
employees.add(Employee(
1000 + i,
_names[_random.nextInt(_names.length - 1)],
_designation[_random.nextInt(_designation.length - 1)],
10000 + _random.nextInt(10000),
));
}
}
final List<String> _names = <String>[
'Welli',
'Blonp',
'Folko',
'Furip',
'Folig',
'Picco',
'Frans',
'Warth',
'Linod',
'Simop',
'Merep',
'Riscu',
'Seves',
'Vaffe',
'Alfki'
];
final List<String> _designation = <String>[
'Project Lead',
'Developer',
'Manager',
'Designer',
'System Analyst',
'CEO'
];
}
{% endhighlight %}
{% endtabs %}
**NOTE**
Download demo application from [GitHub](https://github.com/SyncfusionExamples/how-to-load-rows-on-demand-in-Syncfusion-Flutter-datatable).
![flutter datagrid shows load more button behavior](images/load-more/flutter-datagrid-load-more-button.gif)

Просмотреть файл

@ -1,254 +0,0 @@
---
layout: post
title: Localization in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about localization of static strings in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Localization in Flutter DataPager (SfDataPager)
By default, the [SfDataPager](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager-class.html) widget supports US English localizations. You can change the other languages by specifying the `MaterialApp` properties and adding the `flutter_localizations` package to your application.
As of February 2020, [flutter package](https://flutter.dev/docs/development/accessibility-and-localization/internationalization) supports 77 languages.
To use `flutter_localizations`, add the package as dependency to `pubspec.yaml` file.
{% highlight dart %}
dependencies:
flutter_localizations:
sdk: flutter
{% endhighlight %}
Next, import the `flutter_localizations` library and specify [localizationsDelegates](https://api.flutter.dev/flutter/widgets/LocalizationsDelegate-class.html) and `supportedLocales` for `MaterialApp`.
{% tabs %}
{% highlight Dart %}
import 'package:flutter_localizations/flutter_localizations.dart';
final int rowsPerPage = 15;
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('zh'),
const Locale('ar'),
const Locale('ja'),
],
locale: const Locale('zh'),
home: Scaffold(
appBar: AppBar(
title: Text('DataPager'),
),
body: LayoutBuilder(
builder: (context, constraints) {
return Column(
children: [
SizedBox(
height: constraints.maxHeight - 60,
width: constraints.maxWidth,
child: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
Container(
height: 60,
width: constraints.maxWidth,
child: SfDataPager(
delegate: _employeeDataSource,
pageCount: employees.length / rowsPerPage,
visibleItemsCount: 5,
direction: Axis.horizontal,
),
)
],
);
},
),
),
);
}
{% endhighlight %}
{% endtabs %}
## Localize the static string in DataPager
Static strings in the data pager can be localized using the [syncfusion_localizations](https://pub.dev/packages/syncfusion_localizations) package and specifying `localizationsDelegates` in `MaterialApp`.
To use `syncfusion_localizations`, add the package as dependency to `pubspec.yaml` file.
{% highlight dart %}
dependencies:
syncfusion_localizations: ^18.3.35
{% endhighlight %}
Next, import the `syncfusion_localizations` library.
{% highlight dart %}
import 'package:syncfusion_localizations/syncfusion_localizations.dart';
{% endhighlight %}
Then, declare the [SfGlobalLocalizations.delegate](https://pub.dev/documentation/syncfusion_localizations/latest/syncfusion_localizations/SfGlobalLocalizations/delegate-constant.html) in the `localizationsDelegates`, which is used to localize the static string available in data pager and specify the `supportedLocales` as well.
{% tabs %}
{% highlight Dart %}
final int rowsPerPage = 15;
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
SfGlobalLocalizations.delegate
],
supportedLocales: [
const Locale('zh'),
const Locale('ar'),
const Locale('ja'),
],
locale: const Locale('zh'),
home: Scaffold(
appBar: AppBar(
title: Text('DataPager'),
),
body: LayoutBuilder(
builder: (context, constraints) {
return Column(
children: [
SizedBox(
height: constraints.maxHeight - 60,
width: constraints.maxWidth,
child: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
Container(
height: 60,
width: constraints.maxWidth,
child: SfDataPager(
delegate: _employeeDataSource,
pageCount: employees.length / rowsPerPage,
visibleItemsCount: 5,
direction: Axis.horizontal,
),
)
],
);
},
),
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datapager with localization](images/localization/flutter-datapager-localization.png)

Просмотреть файл

@ -1,817 +0,0 @@
---
layout: post
title: Paging in Flutter DataGrid | DataPager | Syncfusion
description: Learn here all about paging feature and how to customize its apperance in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Paging in Flutter DataGrid (SfDataGrid)
The datagrid interactively supports the manipulation of data using [SfDataPager](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager-class.html) control. This provides support to load data in segments when dealing with large volumes of data. `SfDataPager` can be placed above or below based on the requirement to easily manage data paging.
The datagrid performs paging of data using the `SfDataPager`. To enable paging, follow below procedure
* Create a new `SfDataPager` widget, and set the [SfDataGrid.DataGridSource](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource-class.html) to the [SfDataPager.delegate](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/delegate.html) property.
* Set the number of pages required to be displayed in data pager by setting the [SfDataPager.pageCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/pageCount.html) property.
* Set the number of buttons that should be displayed in view by setting the [SfDataPager.visibleItemsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/visibleItemsCount.html) property.
* You can load the data for the specific page in `handlePageChanges` method. This method is called for every page navigation from data pager.
N> The `SfDataPager.visibleItemsCount` property default value is 5.
The following code example illustrates using `SfDataPager` with the datagrid control:
{% tabs %}
{% highlight Dart %}
final int rowsPerPage = 15;
final double dataPagerHeight = 60.0;
List<OrderInfo> orders = [];
List<OrderInfo> paginatedOrders = [];
final OrderInfoDataSource _orderInfoDataSource = OrderInfoDataSource();
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraint) {
return Column(
children: [
SizedBox(
height: constraint.maxHeight - dataPagerHeight,
width: constraint.maxWidth,
child: SfDataGrid(
source: _orderInfoDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'customerID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
)),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
Container(
height: dataPagerHeight,
child: SfDataPager(
delegate: _orderInfoDataSource,
pageCount: orders.length / rowsPerPage,
direction: Axis.horizontal,
),
)
],
);
});
}
class OrderInfoDataSource extends DataGridSource{
OrderInfoDataSource() {
paginatedOrders = orders.getRange(0, 19).toList(growable: false);
buildPaginateDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
if (dataGridCell.columnName == 'orderID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
),
);
} else if (dataGridCell.columnName == 'customerID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
} else if (dataGridCell.columnName == 'orderDate') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
DateFormat.yMd().format(dataGridCell.value).toString(),
overflow: TextOverflow.ellipsis,
));
} else {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
NumberFormat.currency(locale: 'en_US', symbol: '\$')
.format(dataGridCell.value)
.toString(),
overflow: TextOverflow.ellipsis,
));
}
}).toList());
}
@override
Future<bool> handlePageChange(int oldPageIndex, int newPageIndex) async {
int startIndex = newPageIndex * rowsPerPage;
int endIndex = startIndex + rowsPerPage;
if(startIndex < orders.length && endIndex <= orders.length){
paginatedOrders = orders.getRange(startIndex, endIndex).toList(growable: false);
buildPaginatedDataGridRows();
notifyListeners();
}else{
paginatedOrders = [];
}
return true;
}
void buildPaginatedDataGridRows() {
dataGridRows = paginatedOrders.map<DataGridRow>((dataGridRow) {
return DataGridRow(cells: [
DataGridCell(columnName: 'orderID', value: dataGridRow.orderID),
DataGridCell(columnName: 'customerID', value: dataGridRow.customerID),
DataGridCell(columnName: 'orderDate', value: dataGridRow.orderData),
DataGridCell(columnName: 'freight', value: dataGridRow.freight),
]);
}).toList(growable: false);
}
}
{% endhighlight %}
{% endtabs %}
![flutter datapager with datagrid](images/paging/flutter-datapager.png)
## Callbacks
The SfDataPager provides [onPageNavigationStart](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/onPageNavigationStart.html) and [onPageNavigationEnd](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/onPageNavigationEnd.html) callbacks to listen the page navigation in widget level.
Typically, these callbacks are used to show and hide loading indicator.
{% tabs %}
{% highlight Dart %}
final OrderInfoDataSource _orderInfoDataSource = OrderInfoDataSource();
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) {
return Row(children: [
Column(
children: [
SizedBox(
height: constraints.maxHeight - 60,
width: constraints.maxWidth,
child: buildDataGrid(constraints)),
Container(
height: 60,
width: constraints.maxWidth,
child: SfDataPager(
pageCount: orders.length / rowsPerPage,
direction: Axis.horizontal,
onPageNavigationStart: (int pageIndex) {
//You can do your customization
},
delegate: _orderInfoDataSource,
onPageNavigationEnd: (int pageIndex) {
//You can do your customization
},
),
)
],
),
]);
},
),
);
}
Widget buildDataGrid(BoxConstraints constraint) {
return SfDataGrid(
source: _orderInfoDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'customerID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
)),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
class OrderInfoDataSource extends DataGridSource{
OrderInfoDataSource() {
paginatedOrders = orders.getRange(0, 19).toList(growable: false);
buildPaginatedDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
if (dataGridCell.columnName == 'orderID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
),
);
} else if (dataGridCell.columnName == 'customerID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
} else if (dataGridCell.columnName == 'orderDate') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
DateFormat.yMd().format(dataGridCell.value).toString(),
overflow: TextOverflow.ellipsis,
));
} else {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
NumberFormat.currency(locale: 'en_US', symbol: '\$')
.format(dataGridCell.value)
.toString(),
overflow: TextOverflow.ellipsis,
));
}
}).toList());
}
@override
Future<bool> handlePageChange(int oldPageIndex, int newPageIndex) async {
int startIndex = newPageIndex * rowsPerPage;
int endIndex = startIndex + rowsPerPage;
if(startIndex < orders.length && endIndex <= orders.length){
paginatedOrders = orders.getRange(startIndex, endIndex).toList(growable: false);
buildPaginatedDataGridRows();
notifyListeners();
}else{
paginatedOrders = [];
}
return true;
}
void buildPaginatedDataGridRows() {
dataGridRows = paginatedOrders.map<DataGridRow>((dataGridRow) {
return DataGridRow(cells: [
DataGridCell(columnName: 'orderID', value: dataGridRow.orderID),
DataGridCell(columnName: 'customerID', value: dataGridRow.customerID),
DataGridCell(columnName: 'orderDate', value: dataGridRow.orderData),
DataGridCell(columnName: 'freight', value: dataGridRow.freight),
]);
}).toList(growable: false);
}
}
{% endhighlight %}
{% endtabs %}
## Asynchronous data loading
You can load the data asynchronously to the `SfDataPager` by overriding the `handlePageChange` method and await the method while loading the data.
You can use `onPageNavigationStart` and `onPageNavigationEnd` callbacks to show and hide the loading indicator when navigating between pages.
In the below example, we have set await for 2000ms and displayed the loading indicator until 2000ms.
{% tabs %}
{% highlight Dart %}
final OrderInfoDataSource _orderInfoDataSource = OrderInfoDataSource();
bool showLoadingIndicator = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) {
return Row(children: [
Column(
children: [
SizedBox(
height: constraints.maxHeight - 60,
width: constraints.maxWidth,
child: buildStack(constraints)),
Container(
height: 60,
width: constraints.maxWidth,
child: SfDataPager(
pageCount:
orders.length / rowsPerPage,
direction: Axis.horizontal,
onPageNavigationStart: (int pageIndex) {
setState(() {
showLoadingIndicator = true;
});
},
delegate: _orderInfoDataSource,
onPageNavigationEnd: (int pageIndex) {
setState(() {
showLoadingIndicator = false;
});
},
),
)
],
),
]);
},
),
);
}
Widget buildDataGrid(BoxConstraints constraint) {
return SfDataGrid(
source: _orderInfoDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order ID',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'customerID',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Customer Name',
overflow: TextOverflow.ellipsis,
),
)),
GridTextColumn(
columnName: 'orderDate',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Order Date',
overflow: TextOverflow.ellipsis,
),
),
),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
Widget buildStack(BoxConstraints constraints) {
List<Widget> _getChildren() {
final List<Widget> stackChildren = [];
stackChildren.add(buildDataGrid(constraints));
if (showLoadingIndicator) {
stackChildren.add(Container(
color: Colors.black12,
width: constraints.maxWidth,
height: constraints.maxHeight,
child: Align(
alignment: Alignment.center,
child: CircularProgressIndicator(
strokeWidth: 3,
),
),
));
}
return stackChildren;
}
return Stack(
children: _getChildren(),
);
}
class OrderInfoDataSource extends DataGridSource{
OrderInfoDataSource() {
paginatedOrders = orders.getRange(0, 19).toList(growable: false);
buildPaginateDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
if (dataGridCell.columnName == 'orderID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
),
);
} else if (dataGridCell.columnName == 'customerID') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
} else if (dataGridCell.columnName == 'orderDate') {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
DateFormat.yMd().format(dataGridCell.value).toString(),
overflow: TextOverflow.ellipsis,
));
} else {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.center,
child: Text(
NumberFormat.currency(locale: 'en_US', symbol: '\$')
.format(dataGridCell.value)
.toString(),
overflow: TextOverflow.ellipsis,
));
}
}).toList());
}
@override
Future<bool> handlePageChange(int oldPageIndex, int newPageIndex) async {
int startIndex = newPageIndex * rowsPerPage;
int endIndex = startIndex + rowsPerPage;
if(startIndex < orders.length && endIndex <= orders.length){
await Future.delayed(Duration(milliseconds: 2000));
paginatedOrders = orders.getRange(startIndex, endIndex).toList(growable: false);
buildPaginatedDataGridRows();
notifyListeners();
}else{
paginatedOrders = [];
}
return true;
}
void buildPaginatedDataGridRows() {
dataGridRows = paginatedOrders.map<DataGridRow>((dataGridRow) {
return DataGridRow(cells: [
DataGridCell(columnName: 'orderID', value: dataGridRow.orderID),
DataGridCell(columnName: 'customerID', value: dataGridRow.customerID),
DataGridCell(columnName: 'orderDate', value: dataGridRow.orderData),
DataGridCell(columnName: 'freight', value: dataGridRow.freight),
]);
}).toList(growable: false);
}
}
{% endhighlight %}
{% endtabs %}
![flutter datapager with asynchronous loading](images/paging/flutter-datapager-asynchronous-loading.gif)
>**NOTE**
Download demo application from [GitHub](https://github.com/SyncfusionExamples/how-to-show-loading-indicator-on-loading-page-in-flutter-datatable).
## Programmatic page navigation
The `SfDataPager` provides the support to navigate between the pages programmatically using [controller](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController-class.html) with following options,
* [nextPage](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataPagerController/nextPage.html)
* [previousPage](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataPagerController/previousPage.html)
* [LastPage](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataPagerController/lastPage.html)
* [firstPage](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataPagerController/firstPage.html)
The following code example shows how to navigate the previous page programmatically,
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(builder: (context, constraint) {
return Column(
children: [
MaterialButton(
onPressed: () {
controller.previousPage();
},
child: Text('Move Previous page'),
),
SizedBox(
height: constraint.maxHeight - 120,
width: constraint.maxWidth,
child: _buildDataGrid()),
Container(
height: 60,
child: Align(
alignment: Alignment.center,
child: SfDataPager(
delegate: orderInfoDataSource,
initialPageIndex: index,
controller: controller,
pageCount: orderInfoDataSource.orders.length /
orderInfoDataSource.rowsPerPage,
direction: Axis.horizontal,
)),
)
],
);
}),
);
}
{% endhighlight %}
{% endtabs %}
## Orientation
`SfDataPager` allows you to arrange the child elements either horizontally or vertically. This can be achieved by using the [direction](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/direction.html) Property. `direction` is an Enum type.
<table>
<tr>
<th>
Enum
</th>
<th>
Description</th>
</tr>
<tr>
<td>
horizontal
</td>
<td>
This is the default enum value for direction. Arranges all the navigation buttons and numeric buttons horizontally.{{'![flutter datapager in horizontal direction](images/paging/flutter-datapager-direction-horizontal.png)'|markdownify}}
</td>
</tr>
<tr>
<td>
vertical
</td>
<td>
Arranges all the navigation buttons and numeric buttons vertically by setting Axis.vertical to direction property.{{'![flutter datapager in vertical direction](images/paging/flutter-datapager-direction-vertical.png)'|markdownify}}
</td>
</tr>
</table>
## Appearance
SfDataPager allows to customize the appearance of the data pager using the [SfDataPagerThemeData](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataPagerThemeData-class.html) in [SfDataPagerTheme](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataPagerTheme-class.html). The `SfDataPager` should be wrapped inside the `SfDataPagerTheme`.
Import the following class from the [syncfusion_flutter_core](https://pub.dev/packages/syncfusion_flutter_core) package.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_core/theme.dart';
{% endhighlight %}
{% endtabs %}
The following code example illustrates using `SfDataPagerThemeData` with the data pager control
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataPagerTheme(
data: SfDataPagerThemeData(
itemColor: Colors.white,
selectedItemColor: Colors.lightGreen,
itemBorderRadius: BorderRadius.circular(5),
backgroundColor: Colors.teal,
),
child: SfDataPager(
delegate: _orderInfoDataSource,
pageCount: orders.length / rowsPerPage,
direction: Axis.horizontal,
),
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datapager with customization](images/paging/flutter-datapager-customization.png)
## Change the number of visible items (buttons) in view
You can change the number of visible items i.e. page buttons in view by using the [SfDataPager.visibleItemsCount](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/visibleItemsCount.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter DataGrid Sample'),
),
body: LayoutBuilder(builder: (context, constraint) {
return Column(
children: [
SizedBox(
height: constraint.maxHeight - dataPagerHeight,
width: constraint.maxWidth,
child: _buildDataGrid()),
Container(
height: dataPagerHeight,
child: SfDataPager(
visibleItemsCount: 1,
delegate: orderInfoDataSource,
pageCount: orderInfoDataSource.orders.length /
orderInfoDataSource.rowsPerPage,
direction: Axis.horizontal,
),
)
],
);
}));
}
{% endhighlight %}
{% endtabs %}
## Load any widget in page button
You can load any widget to page button by using [SfDataPager.pageItemBuilder](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataPager/pageItemBuilder.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter DataGrid Sample'),
),
body: LayoutBuilder(builder: (context, constraint) {
return Column(
children: [
SizedBox(
height: constraint.maxHeight - dataPagerHeight,
width: constraint.maxWidth,
child: _buildDataGrid()),
Container(
height: dataPagerHeight,
child: SfDataPagerTheme(
data: SfDataPagerThemeData(
itemBorderColor: Colors.blue,
itemBorderWidth: 1,
backgroundColor: Colors.transparent,
itemBorderRadius: BorderRadius.circular(0),
),
child: SfDataPager(
pageItemBuilder: (String value) {
return Container(
child: Text(
value,
style: TextStyle(
fontSize: 10, fontWeight: FontWeight.w700),
));
},
delegate: orderInfoDataSource,
pageCount: orderInfoDataSource.orders.length /
orderInfoDataSource.rowsPerPage,
direction: Axis.horizontal,
),
),
)
],
);
}));
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,393 +0,0 @@
---
layout: post
title: Pull to Refresh in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about pull to refresh feature of Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Pull to Refresh in Flutter DataGrid (SfDataGrid)
The Flutter DataTable provides support to add more data at runtime by using the PullToRefresh feature.
You can simply enable the PullToRefresh option by setting the [SfDataGrid.allowPullToRefresh](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/allowPullToRefresh.html) property to `true` and override the [DataGridSource.handleRefresh](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/handleRefresh.html) method to include the data which is going to add to the data source at runtime and then notify the data grid about the changes.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
allowPullToRefresh: true,
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource() {
buildDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
Future<void> handleRefresh() async {
await Future.delayed(Duration(seconds: 5));
_addMoreRows(_employees, 15);
buildDataGridRows();
notifyListeners();
}
void buildDataGridRows() {
dataGridRows = _employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
void _addMoreRows(List<Employee> employees, int count) {
final Random _random = Random();
final startIndex = employees.isNotEmpty ? employees.length : 0,
endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
employees.add(Employee(
1000 + i,
_names[_random.nextInt(_names.length - 1)],
_designation[_random.nextInt(_designation.length - 1)],
10000 + _random.nextInt(10000),
));
}
}
final List<String> _names = <String>[
'Welli',
'Blonp',
'Folko',
'Furip',
'Folig',
'Picco',
'Frans',
'Warth',
'Linod',
'Simop',
'Merep',
'Riscu',
'Seves',
'Vaffe',
'Alfki'
];
final List<String> _designation = <String>[
'Project Lead',
'Developer',
'Manager',
'Designer',
'System Analyst',
'CEO'
];
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows default view of refresh indicator](images/pull-to-refresh/flutter-datagrid-pull-to-refresh.gif)
## Customizing the refresh indicator
SfDataGrid displays the [RefreshIndicator](https://api.flutter.dev/flutter/material/RefreshIndicator-class.html) for `pull to refresh` action. So, you can set the color and background color of refresh indicator by using [ThemeData.accentColor](https://api.flutter.dev/flutter/material/ThemeData/accentColor.html) and [ThemeData.canvasColor](https://api.flutter.dev/flutter/material/ThemeData/canvasColor.html) properties.
You can also change the stroke width and displacement of refresh indicator by using [SfDataGrid.refreshIndicatorStrokeWidth](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/refreshIndicatorStrokeWidth.html) and [SfDataGrid.refreshIndicatorDisplacement](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/refreshIndicatorDisplacement.html) properties.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
accentColor: Colors.white,
canvasColor: Colors.lightBlue,
),
child: SfDataGrid(
allowPullToRefresh: true,
source: employeeDataSource,
refreshIndicatorStrokeWidth: 3.0,
refreshIndicatorDisplacement: 60.0,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customized refresh indicator](images/pull-to-refresh/flutter-datagrid-customized-pull-to-refresh-indicator.gif)
## Programmatic Pull to Refresh
If you want to refresh data without showing a refresh indicator, you can pass `false` to the `showRefreshIndicator` optional parameter of [refresh](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGridState/refresh.html) method. By doing this, `DataGridSource.handleRefresh` method will be called without showing the `RefreshIndicator` in UI.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
final GlobalKey<SfDataGridState> key = GlobalKey<SfDataGridState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DataGrid Demo'),
),
body: SfDataGrid(
key: key,
allowPullToRefresh: true,
source: employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () {
key.currentState.refresh();
},
),
);
}
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource({List<Employee> employeesData}) {
buildDataGridRows();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
Future<void> handleRefresh() async {
await Future.delayed(Duration(seconds: 5));
_addMoreRows(_employees, 15);
buildDataGridRows();
notifyListeners();
}
void buildDataGridRows() {
dataGridRows = employees
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(
columnName: 'salary', value: dataGridRow.salary),
]))
.toList();
}
void _addMoreRows(List<Employee> employees, int count) {
final Random _random = Random();
final startIndex = employees.isNotEmpty ? employees.length : 0,
endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
employees.add(Employee(
1000 + i,
_names[_random.nextInt(_names.length - 1)],
_designation[_random.nextInt(_designation.length - 1)],
10000 + _random.nextInt(10000),
));
}
}
final List<String> _names = <String>[
'Welli',
'Blonp',
'Folko',
'Furip',
'Folig',
'Picco',
'Frans',
'Warth',
'Linod',
'Simop',
'Merep',
'Riscu',
'Seves',
'Vaffe',
'Alfki'
];
final List<String> _designation = <String>[
'Project Lead',
'Developer',
'Manager',
'Designer',
'System Analyst',
'CEO'
];
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows programmatic refresh indicator](images/pull-to-refresh/flutter-datagrid-programmatic-pull-to-refresh.gif)

Просмотреть файл

@ -1,134 +0,0 @@
---
layout: post
title: RTL support in Flutter DataGrid | DataTable | Syncfusion
description: Learn here about the right to left (RTL) support in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
## Right to Left (RTL) in Flutter DataGrid (SfDataGrid)
SfDataGrid supports right-to-left rendering. The columns will be rendered based on LTR and RTL direction.
## RTL rendering ways
Right to left rendering can be switched in the following ways:
### Wrapping the SfDataGrid with Directionality widget
To change the rendering direction from right to left, wrap the [SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) widget inside the [Directionality](https://api.flutter.dev/flutter/widgets/Directionality-class.html) widget and set the [textDirection](https://api.flutter.dev/flutter/widgets/Directionality/textDirection.html) property as [TextDirection.rtl](https://api.flutter.dev/flutter/dart-ui/TextDirection-class.html).
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: SfDataGrid(
source: employeeDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.all(16.0),
alignment: Alignment.center,
child: Text(
'ID',
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text('Name'))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text('Salary'))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
### Changing the locale to RTL languages
To change the datagrid rendering direction from right to left, change the [locale](https://api.flutter.dev/flutter/material/MaterialApp/locale.html) to any of the RTL languages such as Arabic, Persian, Hebrew, Pashto, and Urdu.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: <Locale>[
Locale('en'),
Locale('ar'),
// ... other locales the app supports
],
locale: Locale('ar'),
home: SfDataGrid(
source: employeeDataSource,
columnWidthMode: ColumnWidthMode.fill,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.all(16.0),
alignment: Alignment.center,
child: Text(
'ID',
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text('Name'))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.all(8.0),
alignment: Alignment.center,
child: Text('Salary'))),
],
),
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,318 +0,0 @@
---
layout: post
title: Row Height Customization in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to customize the row heights in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Row Height Customization in Flutter DataGrid (SfDataGrid)
This section explains about options to customize the header row height and the row height of all the grid rows or particular row based on your requirements.
## Set height for header row
[SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) allows you to customize the height of the header row by using the [headerRowHeight](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/headerRowHeight.html) property.
{% tabs %}
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDatasource,
headerRowHeight: 70,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows header row with custom height ](images/row-height-customization/flutter-datagrid-header-row-height.jpg)
## Set height for rows except header row
You can customize the height of the grid rows in `SfDataGrid` by using the [rowHeight](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/rowHeight.html) property.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDatasource,
rowHeight: 60,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows rows except header row with custom height](images/row-height-customization/flutter-datagrid-row-height.jpg)
## Refresh row height for specific row
The `SfDataGrid` allows you to update or refresh specific row and it's height when
an underlying data is updated.
You can refresh a specific row and its height by using the [DataGridController.refreshRow](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridController/refreshRow.html) method. This method has following two arguments,
* **rowIndex**- Specify the required row index which is required to refresh. If you specify this, the data alone will be refreshed for a row.
* **recalculateRowHeight** - Decides whether a height of a row should be refreshed along with the data.
If you call `refreshRow` method, `onQueryRowHeight` callback will called for that specific row. So, auto-calculation of height can be recalculated for that row.
In the below example, row data is updated when the `refreshRow` is called in `onPressed` callback of the `FlatButton`.
{% tabs %}
{% highlight Dart %}
List<Employee> _employees = [];
final EmployeeDataSource _employeeDataSource = EmployeeDataSource();
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter DataGrid'),
),
body: Column(
children: [
FlatButton(
child: const Text('Update cell value),
onPressed: () {
_employees[0].id=1010;
_employeeData[0].name = 'Maria Anders';
_employeeData[0].designation = 'Sales Representative';
_employees[0].salary = 25000;
_controller.refreshRow(0);
_employeeDataSource.getData(_employees);
_employeeDataSource.updateDataSource();
}),
SfDataGrid(
source: _employeeDataSource,
controller: _controller,
columnSizer: _columnSizer,
onQueryRowHeight: (RowHeightDetails details) {
if (details.rowIndex == 0) {
return 100.0;
}
return 50.0;
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
In the below example, row data is refreshed along with its row height when the `refreshRow` is called in `onPressed` callback of the `FlatButton`.
{% tabs %}
{% highlight Dart %}
List<Employee> _employees = [];
final EmployeeDataSource _employeeDataSource = EmployeeDataSource();;
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter DataGrid'),
),
body: Column(
children: [
FlatButton(
child: const Text('Update cell value),
onPressed: () {
_employees[0].id=1010;
_employeeData[0].name = 'Maria Anders';
_employeeData[0].designation = 'Sales Representative';
_employees[0].salary = 25000;
_controller.refreshRow(0, recalculateRowHeight: true);
_employeeDataSource.getData(_employees);
_employeeDataSource.updateDataSource();
}),
SfDataGrid(
source: _employeeDataSource,
controller: _controller,
columnSizer: _columnSizer,
onQueryRowHeight: (RowHeightDetails details) {
if (details.rowIndex == 0) {
return 100;
}
return 50.0;
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
],
),
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,567 +0,0 @@
---
layout: post
title: Scrolling in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about scrolling features of Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Scrolling in Flutter DataGrid (SfDataGrid)
SfDataGrid provides support to scroll the content in both the horizontal and vertical direction.
## Show Scrollbars always
You can show horizontal and vertical scrollbars always by using the [SfDataGrid.isScrollbarAlwaysShown](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/isScrollbarAlwaysShown.html) property. When the `isScrollbarAlwaysShown` is set to false, the scrollbar will be shown during scrolling and will fade out otherwise. When it is true, the scrollbar will always be visible and never fade out even after the scrolling.
N> The default value of `isScrollbarAlwaysShown` is false.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
isScrollbarAlwaysShown: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Setting scroll physics for scroll bars
SfDataGrid allows you to set the [ScrollPhysics](https://api.flutter.dev/flutter/widgets/ScrollPhysics-class.html) for horizontal and vertical scrollbars to control how the scroll view should respond to user input by using [horizontalScrollPhysics](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/horizontalScrollPhysics.html) and [verticalScrollPhysics](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/verticalScrollPhysics.html) properties respectively.
N> The default values of `horizontalScrollPhysics` and `verticalScrollPhysics` properties are `AlwaysScrollableScrollPhysics()`.
The following example shows how to disable the horizontal and vertical scrolling by setting `NeverScrollableScrollPhysics()`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
horizontalScrollPhysics: NeverScrollableScrollPhysics(),
verticalScrollPhysics: NeverScrollableScrollPhysics(),
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Programmatic scrolling
The Flutter DataTable provides support to scroll to a particular row and column index programmatically.
### Scroll to cell
Scroll programmatically to a particular cell can be achieved by passing the row and column index in the `scrollToCell` method. SfDataGrid allows to enable or disable the scrolling animation by passing `true` to the `canAnimate` parameter in `scrollToCell` method.
N> The default value of `canAnimate` is `false`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToCell'),
onPressed: () {
_controller.scrollToCell(15, 2);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
![Flutter DataTable shows programmatic scrolling to cell](images/scrolling/flutter-datagrid-programmatic-scrolling-scroll-to-cell.gif)
### Scroll to row
You can scroll programmatically to a particular row by passing the row index in the `scrollToRow` method. SfDataGrid allows to enable or disable the scrolling animation by passing `true` to the `canAnimate` parameter in `scrollToRow` method.
N> The default value of `canAnimate` is `false`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToRow'),
onPressed: () {
_controller.scrollToRow(15);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
### Scroll to column
You can scroll programmatically to a particular column by passing the column index in the `scrollToColumn` method. SfDataGrid allows to enable or disable the scrolling animation by passing `true` to the `canAnimate` parameter in `scrollToColumn` method.
N> The default value of `canAnimate` is `false`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToColumn'),
onPressed: () {
_controller.scrollToColumn(2);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
![Flutter DataTable shows programmatic scrolling to column](images/scrolling/flutter-datagrid-programmatic-scrolling-scroll-to-column.gif)
### Scroll to specific position
`SfDataGrid` allows to position the scrolled row or column in view programmatically by passing `DataGridScrollPosition` to `rowPosition` and `columnPosition` arguments respectively in `scrollToCell` and `position` argument of `scrollToRow` and `scrollToColumn` methods. Below are the four types of positions available,
`makeVisible`: Scroll to make a specified row/column visible in datagrid. If the specified row/column is already in view, scrolling will not occur.
`start`: Scroll to make the row/column positioned at the start of the datagrid.
`center`: Scroll to make the row/column positioned at the center of the datagrid.
`end`: Scroll to make the row/column positioned at the end of the datagrid.
N> The default value of `DataGridScrollPosition` is `Start`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToCell'),
onPressed: () {
_controller.scrollToCell(15, 2,
canAnimate: true,
rowPosition: DataGridScrollPosition.start,
columnPosition: DataGridScrollPosition.start);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
### Scroll to vertical offset
The Flutter DataTable supports to scroll programmatically to a particular vertical offset by passing the offset value to the `scrollToVerticalOffset` method. Also, it allows to enable the scrolling animation by passing `true` to the `canAnimate` parameter in `scrollToVerticalOffset` method.
N> The default value of `canAnimate` is `false`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToVerticalOffset'),
onPressed: () {
_controller.scrollToVerticalOffset(500);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
### Scroll to horizontal offset
The Flutter DataTable supports to scroll programmatically to a particular horizontal offset by passing the offset value to the `scrollToHorizontalOffset` method. Also, it allows to enable the scrolling animation by passing `true` to the `canAnimate` parameter in `scrollToHorizontalOffset` method.
N> The default value of `canAnimate` is `false`.
{% tabs %}
{% highlight Dart %}
final DataGridController _controller = DataGridController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
FlatButton(
child: Text('ScrollToHorizontalOffset'),
onPressed: () {
_controller.scrollToHorizontalOffset(400);
},
),
Expanded( child:SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
controller: _controller,
)),
);
}
{% endhighlight %}
{% endtabs %}
N> The vertical and horizontal scrolled offset can be retrieved by using `DataGridController.verticalOffset` and `DataGridController.horizontalOffset` properties.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,645 +0,0 @@
---
layout: post
title: Sorting in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to sort a column or multiple columns with tristate sorting in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Sorting in Flutter Datagrid (SfDataGrid)
The datagrid provides the built-in support to sort one or more columns by setting the [SfDataGrid.allowSorting](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/allowSorting.html) property to true. When sorting is applied, the datagrid automatically rearranges the data to match with the current sort criteria. When `SfDataGrid.allowSorting` is true, you can sort the data simply by tapping the column header. Once sorting is applied, the datagrid shows a sort icon in the respective column header indicating the sort direction.
## Programmatic sorting
The datagrid provides support to sort the columns programmatically. You can manually define the [SortColumnDetails](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SortColumnDetails-class.html) objects, and add it in the [SfDataGrid.source.sortedColumns](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/sortedColumns.html) collection. The datagrid sorts the data based on the `SortColumnDetails` objects added to this collection. If you want to perform sorting at run time, you should call [SfDataGrid.source.sort()](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/sort.html) method after adding the `SortColumnDetails` to the `SfDataGrid.source.sortedColumns` collection.
The `SortColumnDetails` object holds the following two properties:
* [name](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SortColumnDetails/name.html) : Name of the column to be sorted.
* [sortDirection](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SortColumnDetails/sortDirection.html) : Specifies the ascending or descending direction.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SfDataGrid(
source: _employeeDataSource,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: FlatButton(
onPressed: () {
_employeeDataSource.sortedColumns.add(SortColumnDetails(
name: 'name',
sortDirection: DataGridSortDirection.ascending));
_employeeDataSource.sort();
},
child: Text('Apply sort')),
)
],
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows programmatical sorting](images/sorting/flutter-datagrid-programmatical-sorting.png)
## Multi-column sorting
The datagrid sorts the data against more than one columns by setting the [SfDataGrid.allowMultiColumnSorting](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/allowMultiColumnSorting.html) property to true. The number of columns by which the data can be sorted is unlimited. To apply sorting for multiple columns, tap the desired column headers after setting the `SfDataGrid.allowMultiColumnSorting` property.
To apply sorting for multiple columns in web and desktop, you can click the column header by pressing the <kbd>Ctrl</kbd> key.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
allowMultiColumnSorting: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows multi-column sorting](images/sorting/flutter-datagrid-multicolumn-sorting.gif)
## Tri-state sorting
In addition to sort the data in ascending/descending order, the SfDataGrid unsort the data in the original order by clicking the header again after sorting to descending order by setting the [SfDataGrid.allowTriStateSorting](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/allowTriStateSorting.html) property to true. When this property is set, sorting in each column iterates through three sort states: ascending, descending, and unsort.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
allowMultiColumnSorting: true,
allowTriStateSorting: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows tri-state sorting](images/sorting/flutter-datagrid-tristate-sorting.gif)
## Sort column in double tap
By default, column gets sorted when column header clicked. This behavior can be changed to sort the column in double click action by setting [SfDataGrid.sortingGestureType](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/sortingGestureType.html) property to `doubleTap`.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
sortingGestureType: SortingGestureType.doubleTap,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
## Show sort number
The datagrid provides support the sequence numbers to display the sorted columns during multi-column sorting by setting [SfDataGrid.showSortNumbers](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/showSortNumbers.html) is set to true. This is applicable when the `SfDataGrid.allowMultiColumnSorting` property is enabled.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
allowMultiColumnSorting: true,
showSortNumbers: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows sort sequence numbers during multi-column sorting](images/sorting/flutter-datagrid-showsortnumbers.gif)
## Disable sorting for an individual column
The data grid disables sorting for an individual column by setting the [GridColumn.allowSorting](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn/allowSorting.html) property to false. The default value of this property is true. So all the columns in the [SfDataGrid.columns](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/columns.html) collection can be sorted when `SfDataGrid.allowSorting` is set to true.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
allowSorting: false,
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
));
}
{% endhighlight %}
{% endtabs %}
## Change the color of sort icon
The color of sort icon can be customized by using [SfDataGridThemeData.sortIconColor]().
The following code describes how to change sort icon color by using [SfDataGridTheme](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridTheme-class.html).
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:syncfusion_flutter_core/theme.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGridTheme(
data: SfDataGridThemeData(
sortIconColor: Colors.redAccent),
child: SfDataGrid(
source: _employeeDataSource,
allowSorting: true,
allowMultiColumnSorting: true,
columns: [
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'city',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'City',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'freight',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Freight',
overflow: TextOverflow.ellipsis,
))),
],
),
));
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customized the sort icon color](images/sorting/flutter-datagrid-customized-sorticon-color.png)
## Custom sorting
The datagrid allows to sort columns based on custom logic. For each column, you can provide different sorting criteria by overriding the following methods from [DataGridSource](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource-class.html),
* **[handleSort](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/handleSort.html)** : This method will be called when you tap the column header and sorting is being applied. You can override this method to provide the entire logic for sorting for columns.
* **[compare](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource/compare.html)** : You can override this method to compare two objects and return the sorting order based on the criteria.
### Sort column based on string length
The following code shows how to perform custom sorting for the columns based on the string length by overriding the `compare` method.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
class EmployeeDataSource extends DataGridSource {
EmployeeDataSource({List<Employee> employeesData}) {
dataGridRows = employeesData
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(columnName: 'salary', value: dataGridRow.salary)
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
int compare(DataGridRow? a, DataGridRow? b, SortColumnDetails sortColumn) {
final String? value1 = a
?.getCells()
.firstWhereOrNull((element) => element.columnName == sortColumn.name)
?.value;
final String? value2 = b
?.getCells()
.firstWhereOrNull((element) => element.columnName == sortColumn.name)
?.value;
int? aLength = value1?.length;
int? bLength = value2?.length;
if (aLength == null || bLength == null) {
return 0;
}
if (aLength.compareTo(bLength) > 0) {
return sortColumn.sortDirection == DataGridSortDirection.ascending
? 1
: -1;
} else if (aLength.compareTo(bLength) == -1) {
return sortColumn.sortDirection == DataGridSortDirection.ascending
? -1
: 1;
} else {
return 0;
}
}
}
{% endhighlight %}
{% endtabs %}
>**NOTE**
Download demo application from [GitHub](https://github.com/SyncfusionExamples/how-to-sort-the-columns-based-on-length-of-the-text-in-Flutter-datagrid).
![flutter datagrid shows custom sorting for the columns based on string length](images/sorting/flutter-datagrid-custom-sorting.png)
### Case-insensitive sorting
The following code shows how to perform custom sorting for the columns based on the case-insensitive by overriding the `compare` method.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
class EmployeeDataSource extends DataGridSource<Employee> {
EmployeeDataSource({List<Employee> employeesData}) {
dataGridRows = employeesData
.map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'id', value: dataGridRow.id),
DataGridCell<String>(columnName: 'name', value: dataGridRow.name),
DataGridCell<String>(
columnName: 'designation', value: dataGridRow.designation),
DataGridCell<int>(columnName: 'salary', value: dataGridRow.salary)
]))
.toList();
}
List<DataGridRow> dataGridRows = [];
@override
List<DataGridRow> get rows => dataGridRows;
@override
DataGridRowAdapter? buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((dataGridCell) {
return Container(
alignment: (dataGridCell.columnName == 'id' ||
dataGridCell.columnName == 'salary')
? Alignment.centerRight
: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
dataGridCell.value.toString(),
overflow: TextOverflow.ellipsis,
));
}).toList());
}
@override
int compare(DataGridRow? a, DataGridRow? b, SortColumnDetails sortColumn) {
if (sortColumn.name == 'name') {
final String? value1 = a
?.getCells()
.firstWhereOrNull((element) => element.columnName == sortColumn.name)
?.value
.toString();
final String? value2 = b
?.getCells()
.firstWhereOrNull((element) => element.columnName == sortColumn.name)
?.value
.toString();
if (value1 == null || value2 == null) {
return 0;
}
if (sortColumn.sortDirection == DataGridSortDirection.ascending) {
return value1.toLowerCase().compareTo(value2.toLowerCase());
} else {
return value2.toLowerCase().compareTo(value1.toLowerCase());
}
}
return super.compare(a, b, sortColumn);
}
}
{% endhighlight %}
{% endtabs %}
>**NOTE**
Download demo application from [GitHub](https://github.com/SyncfusionExamples/how-to-perform-case-insensitive-sorting-in-flutter-datagrid).
![flutter datagrid shows custom sorting for the columns based on case-insensitive](images/sorting/flutter-datagrid-custom-sorting-case-insensitive.png)

Просмотреть файл

@ -1,253 +0,0 @@
---
layout: post
title: Stacked Headers in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to add multi column headers (stacked headers) in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Stacked headers in Flutter Datagrid (SfDataGrid)
The datagrid provides support to display an additional unbound header rows known as [StackedHeaderRows](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/stackedHeaderRows.html) that are spanned across the DataGrid columns. You can group one or more columns under each stacked header.
Each [StackedHeaderRow](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/StackedHeaderRow-class.html) contains [cells](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/StackedHeaderRow/cells.html) that hold a list of [StackedHeaderCell](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/StackedHeaderCell-class.html) where each `StackedHeaderCell` contains a number of child columns. The [StackedHeaderCell.columnNames](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/StackedHeaderCell/columnNames.html) property returns the columns grouped under the stacked header row. The [GridColumn.columnName]() is a unique name used for mapping specific child columns grouped under the same stacked header row. The [StackedHeaderCell.child](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/StackedHeaderCell/child.html) property is used to load any type of widget to the corresponding stacked header cell.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
gridLinesVisibility: GridLinesVisibility.both,
headerGridLinesVisibility: GridLinesVisibility.both,
source: _productDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'customerName',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
))),
],
stackedHeaderRows: <StackedHeaderRow>[
StackedHeaderRow(cells: [
StackedHeaderCell(
columnNames: ['orderId', 'customerName'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Customer Details')))),
StackedHeaderCell(
columnNames: ['productId', 'product'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Product Details'))))
])
],
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows stacked headers](images/stacked-headers/flutter-stacked-headers.png)
## Multi stacked headers
You can provide multiple stacked headers to the datagrid by adding the multiple `StackedHeaderRow` to the `SfDataGrid.stackedHeaderRows` collection.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
gridLinesVisibility: GridLinesVisibility.both,
headerGridLinesVisibility: GridLinesVisibility.both,
source: _productDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'customerName',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
))),
],
stackedHeaderRows: <StackedHeaderRow>[
StackedHeaderRow(cells: [
StackedHeaderCell(
columnNames: ['orderId', 'customerName', 'productId', 'product'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Order Shipment Details')))),
]),
StackedHeaderRow(cells: [
StackedHeaderCell(
columnNames: ['orderId', 'customerName'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Customer Details')))),
StackedHeaderCell(
columnNames: ['productId', 'product'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Product Details'))))
])
],
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows multi stacked headers](images/stacked-headers/flutter-multi-stacked-headers.png)
## Changing row height of stacked headers
You can change the height of stacked header rows by using the [SfDataGrid.onQueryRowHeight](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/onQueryRowHeight.html) callback.
You can also change the row height of stacked header row and column header row by using [headerRowHeight](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/headerRowHeight.html) property.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
gridLinesVisibility: GridLinesVisibility.both,
headerGridLinesVisibility: GridLinesVisibility.both,
source: _productDataSource,
onQueryRowHeight: (RowHeightDetails details) {
if (details.rowIndex == 0) {
return 70.0;
}
return details.rowHeight;;
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'orderId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'customerName',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'productId',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'product',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Product',
overflow: TextOverflow.ellipsis,
))),
],
stackedHeaderRows: <StackedHeaderRow>[
StackedHeaderRow(cells: [
StackedHeaderCell(
columnNames: ['orderId', 'customerName'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Customer Details')))),
StackedHeaderCell(
columnNames: ['productId', 'product'],
child: Container(
color: const Color(0xFFF1F1F1),
child: Center(child: Text('Product Details'))))
])
],
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customization of stacked header row heights](images/stacked-headers/flutter-stacked-header-row-height.png)

Просмотреть файл

@ -1,147 +0,0 @@
---
layout: post
title: Styling feature in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to customize the appearance of DataGrid in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Styling in Flutter DataGrid (SfDataGrid)
The DataGrid supports to change the appearance of the grid by using the [SfDataGridThemeData](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData-class.html) in [SfDataGridTheme](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridTheme-class.html). The DataGrid should be wrapped inside the `SfDataGridTheme`.
## Styling grid lines
Color and thickness of the grid lines can be changed by using the [SfDataGridThemeData.gridLineColor](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/gridLineColor.html) and [SfDataGridThemeData.gridLineStrokeWidth](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfDataGridThemeData/gridLineStrokeWidth.html) properties.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGridTheme(
data: SfDataGridThemeData(
gridLineColor: Colors.amber, gridLineStrokeWidth: 3.0),
child: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
),
),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customizing the grid lines](images/styles/flutter-datagrid-gridline-customization.png)
## Show vertical and horizontal grid lines
To show the vertical and horizontal gridlines, use the following properties.
* [SfDataGrid.gridLinesVisibility](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/gridLinesVisibility.html): To set the border lines for the cells other than header and stacked header cells.
* [SfDataGrid.headerGridLinesVisibility](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/headerGridLinesVisibility.html): To set the border lines only for header and stacked header cells.
The following are the list of options available to customize gridlines,
* Vertical
* Horizontal
* Both
* None
The following code describes how to show vertical and horizontal grid lines for the `SfDataGrid`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfDataGrid(
source: _employeeDataSource,
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
gridLinesVisibility: GridLinesVisibility.both,
headerGridLinesVisibility: GridLinesVisibility.both),
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows both grid lines](images/styles/flutter-datagrid-gridlines.png)

Просмотреть файл

@ -1,216 +0,0 @@
---
layout: post
title: Swiping in Flutter DataGrid | DataTable | Syncfusion
description: Learn here all about how to swipe the data rows in both directions in Syncfusion Flutter DataGrid (SfDataGrid) widget and more.
platform: flutter
control: SfDataGrid
documentation: ug
---
# Swiping in Flutter DataGrid (SfDataGrid)
The Flutter DataTable provides support to swipe a row by setting the [SfDataGrid.allowSwiping](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/allowSwiping.html) property to true. Swipe actions will be displayed when swiping a row from `left to right` or `right to left` direction. The swipe dragging gesture can be restricted to a certain point on the row by setting the [SfDataGrid.swipeMaxOffset](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/swipeMaxOffset.html) property.
## Swipe action builders
The Flutter DataTable enables you to load the desired widget behind the swiped row by using [SfDataGrid.startSwipeActionsBuilder](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/startSwipeActionsBuilder.html) and [SfDataGrid.endSwipeActionsBuilder](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/endSwipeActionsBuilder.html) properties. The swipe widget's width that loads from the actions builder is arranged based on the `SfDataGrid.swipeMaxOffset` property and it takes height based on the current swiping row height.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return SfDataGrid(
allowSwiping: true,
swipeMaxOffset: 100.0,
source: employeeDataSource,
startSwipeActionsBuilder: (BuildContext context, DataGridRow row) {
return GestureDetector(
onTap: () {
_employeeDataSource.dataGridRows.insert(
_employeeDataSource.dataGridRows.indexOf(row),
DataGridRow(cells: [
DataGridCell(value: 1011, columnName: 'id'),
DataGridCell(value: 'Tom Bass', columnName: 'name'),
DataGridCell(value: 'Developer', columnName: 'designation'),
DataGridCell(value: 20000, columnName: 'salary')
]));
_employeeDataSource.updateDataSource();
},
child: Container(
color: Colors.greenAccent,
child: Center(
child: Icon(Icons.add),
),
),
);
},
endSwipeActionsBuilder: (BuildContext context, DataGridRow row) {
return GestureDetector(
onTap: () {
_employeeDataSource.dataGridRows.removeAt(
_employeeDataSource.dataGridRows.indexOf(row));
_employeeDataSource.updateDataSource();
},
child: Container(
color: Colors.redAccent,
child: Center(
child: Icon(Icons.delete),
),
),
);
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
);
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows swiping a row in both directions](images/swiping/flutter-datagrid-swiping.gif)
## Swipe callbacks
The data grid provides the following callbacks to notify the swiping stages:
* [onSwipeStart](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/onSwipeStart.html): Called when the swipe offset changes from its initial value. The swipe action can be canceled by return `false`.
* [onSwipeUpdate](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/onSwipeUpdate.html): Called while swiping a row is in progress. The swipe action can be canceled by return `false`.
* [onSwipeEnd](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid/onSwipeEnd.html): called when the swipe offset value reaches the `SfDataGrid.maxSwipeOffset` indicating that the swipe action is completed.
The swipe callbacks provide the following properties in their arguments:
* [RowIndex](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSwipeUpdateDetails/rowIndex.html): Defines the swiping row index.
* [SwipeDirection](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSwipeUpdateDetails/swipeDirection.html): Defines the swipe direction of the swiped row.
* [SwipeOffset](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSwipeUpdateDetails/swipeOffset.html): Defines the current swipe offset of the row being swiped.
By handling the swipe callbacks, you can use these properties value from the arguments to perform any desired action such as deleting the row, editing the data, etc.
## Customized swipes delete functionality
You can perform customized swipe functionality using the swiping callbacks. The below example shows how to delete a row when swiping a data row from one to another end.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return SfDataGrid(
allowSwiping: true,
swipeMaxOffset: constraints.maxWidth,
source: employeeDataSource,
startSwipeActionsBuilder: (BuildContext context, DataGridRow row) {
return GestureDetector(
onTap: () {
_employeeDataSource.dataGridRows.removeAt(
_employeeDataSource.dataGridRows.indexOf(row));
_employeeDataSource.updateDataSource();
},
child: Container(
color: Colors.green,
padding: EdgeInsets.only(left: 30.0),
alignment: Alignment.centerLeft,
child: Text('Delete', style: TextStyle(color: Colors.white)),
),
);
},
onSwipeUpdate: (details) {
isReachedCenter =
(details.swipeOffset >= constraints.maxWidth / 2) ? true : false;
return true;
},
onSwipeEnd: (details) async {
if (isReachedCenter &&
_employeeDataSource.dataGridRows.isNotEmpty) {
_employeeDataSource.dataGridRows.removeAt(details.rowIndex);
_employeeDataSource.updateDataSource();
isReachedCenter = false;
}
},
columns: <GridColumn>[
GridTextColumn(
columnName: 'id',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'ID',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'name',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Name',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'designation',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'Designation',
overflow: TextOverflow.ellipsis,
))),
GridTextColumn(
columnName: 'salary',
label: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerRight,
child: Text(
'Salary',
overflow: TextOverflow.ellipsis,
))),
],
);
});
}
{% endhighlight %}
{% endtabs %}
![flutter datagrid shows customized swiping delete functionality](images/swiping/flutter-datagrid-customized-swiping-delete-funtionality.gif)

Просмотреть файл

@ -1,388 +0,0 @@
---
layout: post
title: Getting started with Flutter Maps widget | Syncfusion
description: Learn here about getting started with Syncfusion Flutter Maps (SfMaps) widget, its elements, and more.
platform: Flutter
control: SfMaps
documentation: ug
---
# Getting started with Flutter Maps (SfMaps)
This section explains the steps required to add the maps widget with shape layer and its elements such as data labels, tooltip, assignable colors based on region, and legends. It also explains about adding tile layer with OpenStreetMap. This section covers only basic features needed to know to get started with Syncfusion maps.
To get start quickly with our Flutter Maps widget, you can check on this video.
<style>#flutterMapsVideoTutorial{width : 90% !important; height: 300px !important }</style>
<iframe id='flutterMapsVideoTutorial' src='https://www.youtube.com/embed/TNnAHfXXTFM'></iframe>
## Add Flutter maps to an application
Create a simple project using the instructions given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter maps dependency to your pubspec.yaml file.
{% highlight dart %}
dependencies:
syncfusion_flutter_maps: ^xx.x.xx
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of [`Syncfusion Flutter Maps`](https://pub.dev/packages/syncfusion_flutter_maps/versions) package.
**Get packages**
Run the following command to get the required packages.
{% highlight dart %}
$ flutter pub get
{% endhighlight %}
**Import package**
Import the following package in your Dart code.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_maps/maps.dart';
{% endhighlight %}
{% endtabs %}
## Initialize maps
After importing the package, initialize the maps widget as a child of any widget.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfMaps(),
),
);
}
{% endhighlight %}
{% endtabs %}
## Set GeoJSON data for shape layer from various source
The [`layers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/SfMaps/layers.html) in [`SfMaps`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/SfMaps-class.html) contains collection of either [`MapShapeLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) or [`MapTileLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer-class.html). The actual geographical rendering is done in the each [`MapShapeLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html). The [`source`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/source.html) property of the [`MapShapeLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) is of type [`MapShapeSource`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource-class.html). The [`source`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/source.html) can be set as the .json source from an asset bundle, from network or from Uint8List as bytes. Use the respective constructor depends on the type of the source.
The [`shapeDataField`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeDataField.html) property of the [`MapShapeSource`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource-class.html) is used to refer the unique field name in the .json source to identify each shapes. In [`Mapping the data source`](https://help.syncfusion.com/flutter/maps/getting-started#mapping-the-data-source-for-shape-layer) section of this document, this [`shapeDataField`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeDataField.html) will be used to map with respective value returned in [`primaryValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/primaryValueMapper.html) from the data source.
### From asset bundle
Load .json data from an asset bundle.
N> If you are using the [`MapShapeSource.asset`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/MapShapeSource.asset.html) constructor, you must add the .json file to the assets folder of your root directory and refer the json file path in the `pubspec.yaml` file as shown in the below code snippet. You can get the [`australia.json`](https://www.syncfusion.com/downloads/support/directtrac/general/ze/australia-json-910278184.zip) file here.
{% tabs %}
{% highlight Dart %}
flutter:
uses-material-design: true
assets:
- australia.json
{% endhighlight %}
{% endtabs %}
{% tabs %}
{% highlight Dart %}
late MapShapeSource _dataSource;
@override
void initState() {
_dataSource = MapShapeSource.asset(
'assets/australia.json',
shapeDataField: 'STATE_NAME',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(15),
child: SfMaps(
layers: [
MapShapeLayer(source: _dataSource),
],
),
),
);
}
{% endhighlight %}
{% endtabs %}
### From network
Load .json data from the network.
{% tabs %}
{% highlight Dart %}
late MapShapeSource _dataSource;
@override
void initState() {
_dataSource = MapShapeSource.network(
'http://www.json-generator.com/api/json/get/bVqXoJvfjC?indent=2',
shapeDataField: 'name',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(15),
child: SfMaps(
layers: [
MapShapeLayer(source: _dataSource),
],
),
),
);
}
{% endhighlight %}
{% endtabs %}
### From memory
Load .json data as bytes from `Uint8List`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _fetchJsonData(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
Uint8List bytesData = snapshot.data as Uint8List;
return SfMaps(
layers: [
MapShapeLayer(
source: MapShapeSource.memory(
bytesData,
shapeDataField: 'STATE_NAME',
),
),
],
);
} else {
return CircularProgressIndicator();
}
},
),
);
}
Future<Uint8List> _fetchJsonData() async {
return (await rootBundle.load('assets/australia.json')).buffer.asUint8List();
}
{% endhighlight %}
{% endtabs %}
![maps basic view](images/getting-started/map_basic_view.png)
## Mapping the data source for shape layer
By default, the value specified for the [`shapeDataField`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeDataField.html) in the GeoJSON source will be used in the elements like data labels, tooltip, and legend for their respective shapes. However, it is possible to keep a data source and customize these elements based on the requirement. As mentioned above, [`shapeDataField`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeDataField.html) will be used to map with respective value returned in [`primaryValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/primaryValueMapper.html) from the data source.
{% tabs %}
{% highlight Dart %}
late List<Model> data;
@override
void initState() {
data = <Model>[
Model('New South Wales',
' New\nSouth Wales'),
Model('Queensland', 'Queensland'),
Model('Northern Territory', 'Northern\nTerritory'),
Model('Victoria', 'Victoria'),
Model('South Australia', 'South Australia'),
Model('Western Australia', 'Western Australia'),
Model('Tasmania', 'Tasmania'),
Model('Australian Capital Territory', 'ACT')
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: <MapShapeLayer>[
MapShapeLayer(
source: MapShapeSource.asset(
'assets/australia.json',
shapeDataField: 'STATE_NAME',
dataCount: data.length,
primaryValueMapper: (int index) => data[index].state,
),
),
],
),
);
}
class Model {
Model(this.state, this.stateCode);
String state;
String stateCode;
}
{% endhighlight %}
{% endtabs %}
N>
* Refer the [`MapShapeSource.primaryValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/primaryValueMapper.html), for mapping the data of the data source collection with the respective [`MapShapeSource.shapeDataField`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeDataField.html) in .json source.
* Refer the [`MapShapeSource.bubbleSizeMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/bubbleSizeMapper.html), for customizing the bubble size.
* Refer the [`MapShapeSource.bubbleColorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/bubbleColorValueMapper.html), for customizing the bubble colors.
* Refer the [`MapShapeSource.dataLabelMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/dataLabelMapper.html), for customizing the data label text.
* Refer the [`MapShapeSource.shapeColorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeColorValueMapper.html), for customizing the shape colors.
## Add shape layer maps elements
Add the basic maps elements such as data labels, legend, and tooltip as shown in the below code snippet.
* **Data labels** - You can show data labels using the [`MapShapeLayer.showDataLabels`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/showDataLabels.html) property and also, it is possible to show data labels only for the particular shapes/or show custom text using the [`MapShapeSource.dataLabelMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/dataLabelMapper.html) property.
* **Legend** - You can enable legend using the [`MapShapeLayer.legend`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/legend.html) property. The icons color of the legend is applied based on the colors returned in the [`MapShapeSource.shapeColorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeColorValueMapper.html) property. It is possible to customize the legend icons color and texts using the [`MapShapeSource.shapeColorMappers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeSource/shapeColorMappers.html) property.
* **Tooltip** - You can enable tooltip for the shapes using the [`MapShapeLayer.shapeTooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/shapeTooltipBuilder.html) property. It will be called with the corresponding index every time when you interacts with the shapes i.e., while tapping in touch devices and hover enter in the mouse enabled devices.
{% tabs %}
{% highlight Dart %}
late List<Model> data;
late MapShapeSource dataSource;
@override
void initState() {
data = <Model>[
Model('New South Wales', Color.fromRGBO(255, 215, 0, 1.0),
' New\nSouth Wales'),
Model('Queensland', Color.fromRGBO(72, 209, 204, 1.0), 'Queensland'),
Model('Northern Territory', Colors.red.withOpacity(0.85),
'Northern\nTerritory'),
Model('Victoria', Color.fromRGBO(171, 56, 224, 0.75), 'Victoria'),
Model('South Australia', Color.fromRGBO(126, 247, 74, 0.75),
'South Australia'),
Model('Western Australia', Color.fromRGBO(79, 60, 201, 0.7),
'Western Australia'),
Model('Tasmania', Color.fromRGBO(99, 164, 230, 1), 'Tasmania'),
Model('Australian Capital Territory', Colors.teal, 'ACT')
];
dataSource = MapShapeSource.asset(
'assets/australia.json',
shapeDataField: 'STATE_NAME',
dataCount: data.length,
primaryValueMapper: (int index) => data[index].state,
dataLabelMapper: (int index) => data[index].stateCode,
shapeColorValueMapper: (int index) => data[index].color,
);
super.initState();
}
@override
Widget build(BuildContext context) {
final ThemeData themeData = Theme.of(context);
return Scaffold(
body: Center(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.55,
child: SfMaps(
layers: <MapShapeLayer>[
MapShapeLayer(
source: dataSource,
showDataLabels: true,
legend: MapLegend(MapElement.shape),
shapeTooltipBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(7),
child: Text(data[index].stateCode,
style: themeData.textTheme.caption!
.copyWith(color: themeData.colorScheme.surface)),
);
},
tooltipSettings: MapTooltipSettings(
color: Colors.grey[700],
strokeColor: Colors.white,
strokeWidth: 2),
strokeColor: Colors.white,
strokeWidth: 0.5,
dataLabelSettings: MapDataLabelSettings(
textStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: themeData.textTheme.caption!.fontSize)),
),
],
),
),
),
);
}
class Model {
Model(this.state, this.color, this.stateCode);
String state;
Color color;
String stateCode;
}
{% endhighlight %}
{% endtabs %}
![Maps getting started](images/getting-started/maps_getting_started.png)
## Add tile layer
The [`MapTileLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer-class.html) needs to be added in the [`layers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/SfMaps/layers.html) collection in [`SfMaps`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/SfMaps-class.html). The URL of the providers must be set in the [`MapTileLayer.urlTemplate`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer/urlTemplate.html) property.
Kindly refer the [tile layer](https://help.syncfusion.com/flutter/maps/tile-layer#setting-url-template) section for more information.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
),
],
);
}
{% endhighlight %}
{% endtabs %}
![Maps tile layer getting started](images/getting-started/getting_started_tile_layer.png)

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,720 +0,0 @@
---
layout: post
title: Markers in Flutter Maps widget | Syncfusion
description: Learn here all about the Markers feature of Syncfusion Flutter Maps (SfMaps) widget to customize its appearance including text, icon and more.
platform: Flutter
control: SfMaps
documentation: ug
---
# Markers in Flutter Maps (SfMaps)
Markers can be used to denote the locations. It is possible to use the built-in symbols or display a custom widget at a specific latitude and longitude on a map.
## Adding markers
### Shape layer
You can show markers at any position on the map by providing latitude and longitude position to the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html), which is the widget returns from the [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) property.
The [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) callback will be called number of times equal to the value specified in the [`initialMarkersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/initialMarkersCount.html) property. The default value of the [`initialMarkersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/initialMarkersCount.html) property is `null`.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeSource _dataSource;
@override
void initState() {
_data = const <Model>[
Model('Brazil', -14.235004, -51.92528),
Model('Germany', 51.16569, 10.451526),
Model('Australia', -25.274398, 133.775136),
Model('India', 20.593684, 78.96288),
Model('Russia', 61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
dataCount: _data.length,
primaryValueMapper: (index) => _data[index].country,
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
iconColor: Colors.blue,
);
},
),
],
),
)),
);
}
class Model {
const Model(this.country, this.latitude, this.longitude);
final String country;
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![default marker](images/markers/default_marker.png)
N>
* Refer the [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html), for returning the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html).
* Refer the [`controller`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/controller.html), for dynamically updating the markers.
### Tile layer
You can show markers at any position on the map by providing latitude and longitude position to the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html), which is the widget returns from the [`MapTileLayer.markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) property.
The [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) callback will be called number of times equal to the value specified in the [`initialMarkersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/initialMarkersCount.html) property. The default value of the [`initialMarkersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/initialMarkersCount.html) property is `null`.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
@override
void initState() {
_data = const <Model>[
Model('Brazil', -14.235004, -51.92528),
Model('Germany', 51.16569, 10.451526),
Model('Australia', -25.274398, 133.775136),
Model('India', 20.593684, 78.96288),
Model('Russia', 61.52401, 105.318756)
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SfMaps(
layers: <MapLayer>[
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
iconColor: Colors.blue,
);
},
),
],
),
),
);
}
class Model {
const Model(this.country, this.latitude, this.longitude);
final String country;
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![Tile layer marker](images/markers/tile_layer_marker.png)
N>
* Refer the [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html), for returning the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html).
* Refer the [`controller`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer/controller.html) for dynamically updating the markers.
## Appearance customization
You can customize the built-in markers appearance using the [`iconType`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconType.html), [`iconColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconColor.html), [`iconStrokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconStrokeColor.html), [`iconStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconStrokeWidth.html), and [`size`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/size.html) properties of the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html).
N>
* The default value of the [`iconType`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconType.html) is `MapIconType.circle`.
* The default value of the [`iconStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconStrokeWidth.html) is `1.0`.
* The default value of the [`iconColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/iconColor.html) is `Colors.blue`.
* The default value of the [`size`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker/size.html) is `Size(14.0, 14.0)`.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeSource _dataSource;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
iconType: MapIconType.triangle,
size: Size(18, 18),
iconColor: Colors.green[200],
iconStrokeColor: Colors.green[900],
iconStrokeWidth: 2,
);
},
),
],
),
)),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![marker customization](images/markers/marker_customization.png)
## Adding custom markers
You can show custom marker using the `child` property of the [`MapMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapMarker-class.html) which returns from the [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html).
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late List<Widget> _iconsList;
late MapShapeSource _dataSource;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_iconsList = <Widget>[
Icon(Icons.add_location),
Icon(Icons.airplanemode_active),
Icon(Icons.add_alarm),
Icon(Icons.accessibility_new),
Icon(Icons.account_balance)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: _iconsList[index],
);
},
),
],
),
)),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![custom marker](images/markers/custom_marker.png)
## Adding markers dynamically
You can add markers dynamically using the [`insertMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/insertMarker.html) method. The [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) will be called for the respective index once [`insertMarker`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/insertMarker.html) method is called. The [`controller`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer/controller.html) property of [`MapShapeLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) has to be set with the new instance of [`MapShapeLayerController`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController-class.html).
Marker will be inserted at the given index if the index value is less than or equal to the current available index and the marker will be added as a last item if the index value is greater than the current available index.
N> You can get the current markers count from [`MapShapeLayerController.markersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController/markersCount.html).
### For shape layer
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeLayerController _controller;
late MapShapeSource _dataSource;
late Random random;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
_controller = MapShapeLayerController();
random = Random();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 350,
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: Icon(Icons.add_location),
);
},
controller: _controller,
),
],
),
ElevatedButton(
child: Text('Add marker'),
onPressed: () {
_data.add(Model(-180 + random.nextInt(360).toDouble(),
-55 + random.nextInt(139).toDouble()));
_controller.insertMarker(5);
},
),
],
),
),
)),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
### For Tile layer
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapTileLayerController _controller;
late Random random;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_controller = MapTileLayerController();
random = Random();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 350,
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
SfMaps(
layers: <MapLayer>[
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index) {
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: Icon(Icons.add_location),
);
},
controller: _controller,
),
],
),
ElevatedButton(
child: Text('Add marker'),
onPressed: () {
_data.add(Model(-180 + random.nextInt(360).toDouble(),
-55 + random.nextInt(139).toDouble()));
_controller.insertMarker(5);
},
),
],
),
),
)),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![Add markers dynamically](images/markers/add-markers.gif)
## Updating the existing markers
You can update multiple markers at a same time by passing indices to the [`updateMarkers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/updateMarkers.html) method in the [`MapShapeLayerController`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController-class.html). The [`markerBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/markerBuilder.html) will be called again for the respective indices once [`updateMarkers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/updateMarkers.html) method is called.
N>
* You can get the current markers count from [`MapShapeLayerController.markersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController/markersCount.html).
* You can refer this [`snippet`](https://help.syncfusion.com/flutter/maps/markers#for-tile-layer) to update the markers dynamically for tile layer.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeLayerController _controller;
late Widget _markerWidget;
late MapShapeSource _dataSource;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
_controller = MapShapeLayerController();
_markerWidget = Icon(Icons.add_location);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 350,
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index){
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: _markerWidget,
);
},
controller: _controller,
),
],
),
ElevatedButton(
child: Text('Update marker'),
onPressed: () {
List<int> updateList = <int>[1, 2];
_markerWidget = Icon(Icons.people);
_controller.updateMarkers(updateList);
},
),
],
),
),
)
),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![Update markers dynamically](images/markers/update-markers.gif)
## Deleting a marker
You can remove marker at any index using the [`removeMarkerAt`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/removeMarkerAt.html) method.
N>
* You can get the current markers count from [`MapShapeLayerController.markersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController/markersCount.html).
* You can refer this [`snippet`](https://help.syncfusion.com/flutter/maps/markers#for-tile-layer) to update the markers dynamically for tile layer.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeLayerController _controller;
late MapShapeSource _dataSource;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
_controller = MapShapeLayerController();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 350,
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index){
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: Icon(Icons.add_location),
);
},
controller: _controller,
),
],
),
ElevatedButton(
child: Text('Remove marker'),
onPressed: () {
_controller.removeMarkerAt(4);
},
),
],
),
),
)
),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}
![Remove marker dynamically](images/markers/remove-marker.gif)
## Clearing the markers
You can clear all markers using the [`clearMarkers`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayerController/clearMarkers.html) method.
N>
* You can get the current markers count from [`MapShapeLayerController.markersCount`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayerController/markersCount.html).
* You can refer this [`snippet`](https://help.syncfusion.com/flutter/maps/markers#for-tile-layer) to update the markers dynamically for tile layer.
{% tabs %}
{% highlight Dart %}
late List<Model> _data;
late MapShapeLayerController _controller;
late MapShapeSource _dataSource;
@override
void initState() {
_data = <Model>[
Model(-14.235004, -51.92528),
Model(51.16569, 10.451526),
Model(-25.274398, 133.775136),
Model(20.593684, 78.96288),
Model(61.52401, 105.318756)
];
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'name',
);
_controller = MapShapeLayerController();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 350,
child: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
SfMaps(
layers: <MapLayer>[
MapShapeLayer(
source: _dataSource,
initialMarkersCount: 5,
markerBuilder: (BuildContext context, int index){
return MapMarker(
latitude: _data[index].latitude,
longitude: _data[index].longitude,
child: Icon(Icons.add_location),
);
},
controller: _controller,
),
],
),
ElevatedButton(
child: Text('Clear marker'),
onPressed: () {
_controller.clearMarkers();
},
),
],
),
),
)
),
);
}
class Model {
Model(this.latitude, this.longitude);
final double latitude;
final double longitude;
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,614 +0,0 @@
---
layout: post
title: Adding polygons in Flutter Maps widget | Syncfusion
description: Learn here all about adding the Polygons feature of Syncfusion Flutter Maps (SfMaps) widget and more.
platform: Flutter
control: SfMaps
documentation: ug
---
# Polygons in Flutter Maps (SfMaps)
Polygon layer is a sublayer that renders a group of [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) on [`MapShapeLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) and [`MapTileLayer`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer-class.html). This section helps to learn about how to add the polygons and customize them.
## Adding polygons
The [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) is a collection of [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html). Every single [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) connects multiple coordinates through a [`points`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/points.html) property.
N> It is applicable for both the tile layer and shape layer.
<b>In the shape layer</b>
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
late MapShapeSource dataSource;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1),
PolygonModel(polygon2),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
);
},
).toSet(),
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points);
final List<MapLatLng> points;
}
{% endhighlight %}
{% endtabs %}
<b>In the tile layer</b>
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1),
PolygonModel(polygon2),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
);
},
).toSet(),
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points);
final List<MapLatLng> points;
}
{% endhighlight %}
{% endtabs %}
![Default polygon shape](../images/polygon-layer/default-polygon-shape.png)
## Fill color
You can apply the same color for all [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the [`MapPolygonLayer.color`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/color.html) property. Alternatively, you can apply different colors to each [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the individual [`MapPolygon.color`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/color.html) property.
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
late MapShapeSource dataSource;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1, Colors.greenAccent),
PolygonModel(polygon2, Colors.pinkAccent),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
color: polygons[index].color,
);
},
).toSet(),
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points, this.color);
final List<MapLatLng> points;
final Color color;
}
{% endhighlight %}
{% endtabs %}
![Polygon fill color](../images/polygon-layer/polygon-fill-color.png)
## Stroke width and color
You can apply the same stroke width for all [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the [`MapPolygonLayer.strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/strokeWidth.html) property. Alternatively, you can apply different stroke width to each [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the individual [`MapPolygon.strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/strokeWidth.html) property. The default value of the [`MapPolygonLayer.strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/strokeWidth.html) property is `2`.
You can apply the same stroke color for all [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the [`MapPolygonLayer.strokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/strokeColor.html) property. Alternatively, you can apply different stroke color to each [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) in the [`polygons`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/polygons.html) collection using the individual [`MapPolygon.strokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/strokeColor.html) property.
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
late MapShapeSource dataSource;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1, 3),
PolygonModel(polygon2, 4),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
strokeWidth: polygons[index].width,
strokeColor: Colors.pink,
);
},
).toSet(),
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points, this.width);
final List<MapLatLng> points;
final double width;
}
{% endhighlight %}
{% endtabs %}
![Polygon stroke color](../images/polygon-layer/polygon-stroke-color.png)
## Tap
You can use the [`onTap`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/onTap.html) callback to get a notification if the particular [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) is tapped. You can also customize the tapped [`MapPolygon`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon-class.html) based on the index passed in the callback as shown in the below code snippet.
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
late MapShapeSource dataSource;
late int selectedIndex;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1),
PolygonModel(polygon2),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
selectedIndex = -1;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
color: selectedIndex == index ? Colors.pink : Colors.blue,
onTap: () {
setState(() {
selectedIndex = index;
});
}
);
},
).toSet(),
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points);
final List<MapLatLng> points;
}
{% endhighlight %}
{% endtabs %}
![Polygon tap support](../images/polygon-layer/polygon-tap-support.gif)
## Tooltip
You can show additional information about the polygon drawn using the [`tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapSublayer/tooltipBuilder.html) property.
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late List<MapLatLng> polygon2;
late MapShapeSource dataSource;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(55.7558, 37.6173),
MapLatLng(53.7596, 87.1216),
MapLatLng(61.5240, 105.3188),
];
polygon2 = <MapLatLng>[
MapLatLng(64.2823, -135.0000),
MapLatLng(51.2538, -85.3232),
MapLatLng(48.4284, -123.3656),
];
polygons = <PolygonModel>[
PolygonModel(polygon1),
PolygonModel(polygon2),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
);
},
).toSet(),
tooltipBuilder: (BuildContext context, int index) {
return Padding(
padding: EdgeInsets.all(10),
child: Text('Luxurious \n restaurant'),
);
},
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points);
final List<MapLatLng> points;
}
{% endhighlight %}
{% endtabs %}
## Tooltip customization
You can customize the appearance of the tooltip.
* Background color - Change the background color of the tooltip in the maps using the [`MapTooltipSettings.color`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTooltipSettings/color.html) property.
* Stroke color - Change the stroke color of the tooltip in the maps using the [`MapTooltipSettings.strokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTooltipSettings/strokeColor.html) property.
* Stroke width - Change the stroke width of the tooltip in the maps using the [`MapTooltipSettings.strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTooltipSettings/strokeWidth.html) property.
{% tabs %}
{% highlight Dart %}
late List<PolygonModel> polygons;
late List<MapLatLng> polygon1;
late MapShapeSource dataSource;
late MapZoomPanBehavior zoomPanBehavior;
@override
void initState() {
polygon1 = <MapLatLng>[
MapLatLng(27.6648, -81.5158),
MapLatLng(32.3078, -64.7505),
MapLatLng(18.2208, -66.5901),
];
polygons = <PolygonModel>[
PolygonModel(polygon1),
];
dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(25.3078, -74.7505),
zoomLevel: 4,
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
zoomPanBehavior: zoomPanBehavior,
tooltipSettings: const MapTooltipSettings(
color: Colors.white,
strokeColor: Colors.black,
strokeWidth: 2,
),
sublayers: [
MapPolygonLayer(
polygons: List<MapPolygon>.generate(
polygons.length,
(int index) {
return MapPolygon(
points: polygons[index].points,
);
},
).toSet(),
tooltipBuilder: (BuildContext context, int index) {
return Padding(
padding: EdgeInsets.all(10),
child: Text('Bermuda \n triangle'),
);
},
),
],
),
],
),
);
}
class PolygonModel {
PolygonModel(this.points);
final List<MapLatLng> points;
}
{% endhighlight %}
{% endtabs %}
## Inverted polygon
You can apply color to the inverted polygon by initializing the [`MapPolygonLayer.inverted`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/MapPolygonLayer.inverted.html) constructor. The inner polygon color is transparent and the outer portion of the polygon covered by an overlay color.
You can customize the inverted polygon using the following properties:
* **Stroke color** - Change the stroke color of the polygon using the [`strokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/strokeColor.html) property.
* **Stroke width** - Change the stroke width of the polygon using the [`strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/strokeWidth.html) property. The default value of the `strokeWidth` property is `1`.
* **Overlay color** - Change the outer portion color of the polygon using the [`color`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygonLayer/color.html) property.
* **Tooltip** - You can enable tooltip for the inverted polygon using the [`tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapSublayer/tooltipBuilder.html) property.
N> It is applicable for both the tile layer and shape layer.
I> The individual polygon customization like [`MapPolygon.color`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/color.html), [`MapPolygon.strokeColor`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/strokeColor.html) and [`MapPolygon.strokeWidth`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPolygon/strokeWidth.html) are not supported for the inverted polygon.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior zoomPanBehavior;
late List<MapLatLng> _polygon;
@override
void initState() {
_polygon = <MapLatLng>[
MapLatLng(27.6648, -81.5158),
MapLatLng(32.3078, -64.7505),
MapLatLng(18.2208, -66.5901),
];
zoomPanBehavior = MapZoomPanBehavior(zoomLevel: 4);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
initialFocalLatLng: MapLatLng(25.0119, -73.4842),
sublayers: [
MapPolygonLayer.inverted(
polygons: List<MapPolygon>.generate(
1,
(int index) {
return MapPolygon(
points: _polygon,
);
},
).toSet(),
color: Colors.black.withOpacity(0.3),
strokeColor: Colors.red,
strokeWidth: 1,
),
],
zoomPanBehavior: zoomPanBehavior,
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![Inverted polgon](../images/polygon-layer/inverted-polygon.png)
N> Refer [`tooltip`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapSublayer/tooltipBuilder.html) section, for adding and customizing tooltip to the inverted polygon.

Просмотреть файл

@ -1,752 +0,0 @@
---
layout: post
title: Zooming and Panning in Flutter Maps widget | Syncfusion
description: Learn here all about the Zooming and Panning feature of Syncfusion Flutter Maps (SfMaps) widget and more.
platform: Flutter
control: SfMaps
documentation: ug
---
# Zooming and Panning in Flutter Maps (SfMaps)
It is possible to zoom in and out for any layer to take a closer look at a specific region by pinching the map, scrolling the mouse wheel or track pad, or using the toolbar on the web. Pan the map to navigate across the regions. You can also customize the zoom level and the center point of the initial rendering.
The procedure for zooming and panning for both layers is very similar.
**Shape layer**
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
late MapShapeSource _dataSource;
@override
void initState() {
super.initState();
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
_zoomPanBehavior = MapZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapShapeLayer(
source: _dataSource,
zoomPanBehavior: _zoomPanBehavior,
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
**Tile layer**
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
![Bing maps aerial default](images/zoom-pan/bing_maps_aerial.png)
## Customizing the center latitude and longitude
The [`MapZoomPanBehavior.focalLatLng`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/focalLatLng.html) is the focal point of the map layer based on which zooming happens. It represents the focal latitude and longitude position of the map layer. You can also get the current focalLatLng after interaction using the [MapZoomPanBehavior.focalLatLng](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/focalLatLng.html) property.
To enable panning, set the instance of [`MapZoomPanBehavior`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior-class.html) to [`MapTileLayer.zoomPanBehavior`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/zoomPanBehavior.html). By default, it will be `true`.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(27.1751, 50.0421),
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
![Bing maps aerial focalLatLng](images/zoom-pan/bing_maps_focallatlng.png)
## Update the center latitude and longitude programmatically
You can change the center latitude and longitude of the shape layer programmatically using the [`MapZoomPanBehavior.focalLatLng`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/focalLatLng.html) property.
N> It is applicable for both shape layer and tile layer.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
late MapShapeSource _dataSource;
@override
void initState() {
super.initState();
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
_zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(27.1751, 78.0421),
zoomLevel: 4,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
height: 600,
child: SfMaps(
layers: [
MapShapeLayer(
source: _dataSource,
zoomPanBehavior: _zoomPanBehavior,
),
],
),
),
SizedBox(height: 20),
RaisedButton(
child: Text('Change focalLatLng'),
onPressed: () {
_zoomPanBehavior.focalLatLng = MapLatLng(56.1304, -106.3468);
},
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Customizing the zoom level
You can set the current zoom level of the map layer by using [`MapZoomPanBehavior.zoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/zoomLevel.html) property.
The default [MapZoomPanBehavior.zoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/zoomLevel.html) value is 1 which will show the whole map in the viewport for [MapShapeLayer](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) and the possible bounds for the [MapShapeLayer](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapShapeLayer-class.html) based on the [MapZoomPanBehavior.focalLatLng](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/focalLatLng.html). You can also get the current zoom level after interaction using the [MapZoomPanBehavior.zoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/zoomLevel.html) property.
To enable zooming, set the instance of [`MapZoomPanBehavior`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior-class.html) to [`MapTileLayer.zoomPanBehavior`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapLayer/zoomPanBehavior.html). By default, it will be `true`.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(27.1751, 78.0421),
zoomLevel: 5,
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
![Bing maps aerial zoomlevel](images/zoom-pan/bing_maps_zoomlevel.png)
## Update the zoom level programmatically
You can change the zoom level of the shape layer programmatically using the [`MapZoomPanBehavior.zoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/zoomLevel.html) property.
N> It is applicable for both shape layer and tile layer.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
late MapShapeSource _dataSource;
@override
void initState() {
_dataSource = MapShapeSource.asset(
'assets/world_map.json',
shapeDataField: 'continent',
);
_zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(27.1751, 78.0421),
zoomLevel: 2,
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
height: 600,
child: SfMaps(
layers: [
MapShapeLayer(
source: _dataSource,
zoomPanBehavior: _zoomPanBehavior,
),
],
),
),
SizedBox(height: 20),
RaisedButton(
child: Text('Change zoomLevel'),
onPressed: () {
_zoomPanBehavior.zoomLevel = 7;
},
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Customizing min and max zoom level
You can set the min and max zoom level of the map layer by setting the value to [`MapZoomPanBehavior.minZoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/minZoomLevel.html) and [`MapZoomPanBehavior.maxZoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/maxZoomLevel.html) properties. The minimum and maximum zooming levels can be restricted using these properties respectively. The default values of [`MapZoomPanBehavior.minZoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/minZoomLevel.html) and [`MapZoomPanBehavior.maxZoomLevel`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/maxZoomLevel.html) are 1 and 15 respectively.
However, for [MapTileLayer](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapTileLayer-class.html), [MapZoomPanBehavior.maxZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/maxZoomLevel.html) may slightly vary depends on the providers. Kindly check the respective official website of the map tile providers to know about the maximum zoom level it supports.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior(
focalLatLng: MapLatLng(27.1751, 78.0421),
zoomLevel: 5,
minZoomLevel: 3,
maxZoomLevel: 10,
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
## Double tap zooming
Double tap zooming can be enabled using [`enableDoubleTapZooming`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/enableDoubleTapZooming.html) property. The default value of the [`enableDoubleTapZooming`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/enableDoubleTapZooming.html) is `false`.
N> It is applicable for both tile layer and shape layer.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
_zoomPanBehavior = MapZoomPanBehavior(enableDoubleTapZooming: true);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfMaps(
layers: [
MapTileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
zoomPanBehavior: _zoomPanBehavior,
),
],
),
);
}
{% endhighlight %}
{% endtabs %}
![Double tap zooming](images/zoom-pan/double_tap_zoom.gif)
## Toolbar
You can use the toolbar to customize the visible bound for the web platform. By default, the [MapZoomPanBehavior.showToolbar](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/showToolbar.html) property is `true`.
N>
* Refer [MapZoomPanBehavior.toolbarSettings](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/toolbarSettings.html) for customizing the appearance of the toolbar. You can customize its positions, direction, icon color, item hover color and item background color.
## Zooming callback
Whenever zooming happens, this method is called. If it returns false, zooming will not happen.
[MapZoomDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails-class.html) contains following properties.
* [MapZoomDetails.previousVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/previousVisibleBounds.html) - provides the visible bounds before the current zooming operation completes i.e. current visible bounds.
* [MapZoomDetails.newVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/newVisibleBounds.html) - provides the new visible bounds when the current zoom completes. Hence, if it returns false, there will be no changes in the UI.
* [MapZoomDetails.previousZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/previousZoomLevel.html) - provides the zoom level before the current zooming operation completes i.e. current zoom level.
* [MapZoomDetails.newZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/newZoomLevel.html) - provides the new zoom level when the current zoom completes. Hence, if it returns false, there will be no changes in the UI.
* [MapZoomDetails.globalFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/globalFocalPoint.html) - The global focal point of the pointers in contact with the screen.
* [MapZoomDetails.localFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/localFocalPoint.html) - The local focal point of the pointers in contact with the screen.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior()
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
onWillZoom: (MapZoomDetails detail) {
return true;
},
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
## Panning callback
Whenever panning happens, this method is called. If it returns false, panning will not happen.
[MapPanDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails-class.html) contains following properties.
* [MapPanDetails.previousVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/previousVisibleBounds.html) - provides the visible bounds before the current panning operation completes i.e. current visible bounds.
* [MapPanDetails.newVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/newVisibleBounds.html) - provides the new visible bounds when the current pan completes. Hence, if it returns false, there will be no changes in the UI.
* [MapPanDetails.zoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/zoomLevel.html) - provides the current zoom level.
* [MapPanDetails.delta](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/delta.html) - The difference in pixels between touch start and current touch position.
* [MapPanDetails.globalFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/globalFocalPoint.html) - The global focal point of the pointers in contact with the screen.
* [MapPanDetails.localFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/localFocalPoint.html) - The local focal point of the pointers in contact with the screen.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
onWillPan: (MapPanDetails detail) {
return true;
},
),
],
);
}
return CircularProgressIndicator();
}
);
}
{% endhighlight %}
{% endtabs %}
## Overriding the zoom pan behavior
### Zooming
Whenever zooming happens, this method is called. Subclasses can override this method to do any custom operations based on the details provided in the [MapZoomDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails-class.html).
[MapZoomDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails-class.html) contains following properties,
* [MapZoomDetails.previousVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/previousVisibleBounds.html) - provides the visible bounds before the current zooming operation completes i.e. current visible bounds.
* [MapZoomDetails.newVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/newVisibleBounds.html) - provides the new visible bounds when the current zoom completes. Hence, if the
`super.onZooming(details)` is not called, there will be no changes in the UI.
* [MapZoomDetails.previousZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/previousZoomLevel.html) - provides the zoom level before the current zooming operation completes i.e. current zoom level.
* [MapZoomDetails.newZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/newZoomLevel.html) - provides the new zoom level when the current zoom completes. Hence, if the
`super.onZooming(details)` is not called, there will be no changes in the UI.
* [MapZoomDetails.globalFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/globalFocalPoint.html) - The global focal point of the pointers in contact with the screen.
* [MapZoomDetails.localFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomDetails/localFocalPoint.html) - The local focal point of the pointers in contact with the screen.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = _CustomZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
class _CustomZoomPanBehavior extends MapZoomPanBehavior {
@override
void onZooming(MapZoomDetails details) {
super.onZooming(details);
// Add the code here.
}
}
{% endhighlight %}
{% endtabs %}
N>
* When `super.onZooming(details)` is not called, zooming will not happen.
### Panning
Whenever panning happens, this method is called. Subclasses can override this method to do any custom operations based on the details provided in the [MapPanDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails-class.html).
[MapPanDetails](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails-class.html) contains following properties,
* [MapPanDetails.previousVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/previousVisibleBounds.html) - provides the visible bounds before the current panning operation completes i.e. current visible bounds.
* [MapPanDetails.newVisibleBounds](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/newVisibleBounds.html) - provides the new visible bounds when the current pan completes. Hence, if the
`super.onPanning(details)` is not called, there will be no changes in the UI.
* [MapPanDetails.zoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/zoomLevel.html) - provides the current zoom level.
* [MapPanDetails.delta](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/delta.html) - The difference in pixels between touch start and current touch position.
* [MapPanDetails.globalFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/globalFocalPoint.html) - The global focal point of the pointers in contact with the screen.
* [MapPanDetails.localFocalPoint](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapPanDetails/localFocalPoint.html) - The local focal point of the pointers in contact with the screen.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = _CustomZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
class _CustomZoomPanBehavior extends MapZoomPanBehavior {
@override
void onPanning(MapPanDetails details) {
super.onPanning(details);
// Add the code here
}
}
{% endhighlight %}
{% endtabs %}
N>
* When `super.onPanning(details)` is not called, panning will not happen.
### Reset
You can [`reset`](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/reset.html) the map to the [MapZoomPanBehavior.minZoomLevel](https://pub.dev/documentation/syncfusion_flutter_maps/latest/maps/MapZoomPanBehavior/minZoomLevel.html) by calling this method.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = MapZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
},
),
FlatButton(
onPressed: () {
_zoomPanBehavior.reset();
},
child: Text('Reset Zoom Level'),
),
],
);
}
{% endhighlight %}
{% endtabs %}
### HandleEvent
You can override this method to handle pointer events that hit this render object.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = _CustomZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
class _CustomZoomPanBehavior extends MapZoomPanBehavior {
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
super.handleEvent(event, entry);
// Add the code here
}
}
{% endhighlight %}
{% endtabs %}
### Paint
You can paint this render object into the given context at the given offset.
{% tabs %}
{% highlight Dart %}
late MapZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
super.initState();
_zoomPanBehavior = _CustomZoomPanBehavior();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getBingUrlTemplate(
'https://dev.virtualearth.net/REST/V1/Imagery/Metadata/AerialWithLabels?output=json&uriScheme=https&include=ImageryProviders&key=YOUR_KEY'),
builder: (context, snapshot) {
if (snapshot.hasData) {
return SfMaps(
layers: [
MapTileLayer(
urlTemplate: snapshot.data as String,
zoomPanBehavior: _zoomPanBehavior,
),
],
);
}
return CircularProgressIndicator();
}
);
}
class _CustomZoomPanBehavior extends MapZoomPanBehavior {
@override
void paint(PaintingContext context, Offset offset) {
super.paint(context, offset);
// Add the code here
}
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,90 +0,0 @@
---
layout: post
title: Accessibility in Flutter PDF Viewer widget | Syncfusion
description: Learn here all about the accessibility feature of the Syncfusion Flutter PDF Viewer (SfPdfViewer) widget and more.
platform: Flutter
control: SfPdfViewer
documentation: ug
---
# Accessibility in Flutter PDF Viewer (SfPdfViewer)
## Sufficient contrast
The `SfPdfViewer` [theming](https://help.syncfusion.com/flutter/themes/themes) support provides a consistent and standardized appearance, as well as the ability to set the colors for all UI elements.
The following APIs allow you to customize the colors of the following elements.
* [searchTextHighlightColor](https://help.syncfusion.com/flutter/pdf-viewer/text-search#customize-the-search-text-highlight-color)
* [selectionColor and selectionHandleColor](https://help.syncfusion.com/flutter/pdf-viewer/text-selection#customize-the-text-selection-and-its-handle-color)
## Large fonts
The font size of the [`SfPdfViewer`](https://pub.dev/documentation/syncfusion_flutter_pdfviewer/latest/pdfviewer/SfPdfViewer-class.html) will be automatically scaled based on the device settings.
Also, you can change the font size of the [`SfPdfViewer`](https://pub.dev/documentation/syncfusion_flutter_pdfviewer/latest/pdfviewer/SfPdfViewer-class.html) elements using the following APIs:
* [`Pagination dialog style`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfPdfViewerThemeData/paginationDialogStyle.html)
* [`Bookmark view style`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfPdfViewerThemeData/bookmarkViewStyle.html)
* [`Scroll head style`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfPdfViewerThemeData/scrollHeadStyle.html)
* [`Scroll status style`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfPdfViewerThemeData/scrollStatusStyle.html)
## Keyboard navigation
The `SfPdfViewer` supports the following keyboard interactions.
<table>
<tr>
<th>Key</th>
<th>Description</th>
</tr>
<tr>
<th style="text-align:left" colspan="2">Shortcuts for page navigation</th>
</tr>
<tr>
<td>Home</td>
<td>Navigate to the first page</td>
</tr>
<tr>
<td>End</td>
<td>Navigate to the last page</td>
</tr>
<tr>
<td>Left arrow</td>
<td>Navigate to the previous page</td>
</tr>
<tr>
<td>Right arrow</td>
<td>Navigate to the next page</td>
</tr>
<tr>
<th style="text-align:left" colspan="2">Shortcuts for Zooming</th>
</tr>
<tr>
<td>Ctrl + =</td>
<td>Perform zoom in operation</td>
</tr>
<tr>
</tr>
<tr>
<td>Ctrl + -</td>
<td>Perform zoom out operation</td>
</tr>
<tr>
<td>Ctrl + 0</td>
<td>Retain the zoom level to 1</td>
</tr>
<tr>
<th style="text-align:left" colspan="2">Shortcut for Text Search</th>
</tr>
<tr>
<td>Ctrl + f</td>
<td>Open the search toolbar</td>
</tr>
<tr>
<th style="text-align:left" colspan="2">Shortcut for Text Selection</th>
</tr>
<tr>
<td>Ctrl + c</td>
<td>Copy the selected text</td>
</tr>
</table>

Просмотреть файл

@ -1,25 +0,0 @@
---
layout: post
title: About Flutter PDF Viewer widget | Syncfusion
description: Learn here all about introduction of Syncfusion Flutter PDF Viewer (SfPdfViewer) widget, its features, and more.
platform: Flutter
control: SfPdfViewer
documentation: ug
---
# Flutter PDF Viewer (SfPdfViewer) Overview
The Syncfusion Flutter PDF Viewer widget lets you view PDF documents seamlessly and efficiently in Android, iOS and Web platforms. It has highly interactive and customizable features such as magnification, virtual scrolling, page navigation, text selection, text search, and bookmark navigation.
## Key Features
* **Virtual Scrolling** - Easily scroll through the pages in the document with a fluent experience. The pages are rendered only when required to increase the loading and scrolling performance.
* **Magnification** - The content of the document can be efficiently zoomed in and out.
* **Text selection** - Select text presented in a PDF document.
* **Text search** - Search for text and navigate to all its occurrences in a PDF document instantly.
* **Page navigation** - Navigate to the desired pages instantly.
* **Bookmark navigation** - Bookmarks saved in the document are loaded and made ready for easy navigation. This feature helps navigate the topics bookmarked already within the PDF document.
* **Document link annotation navigation** - Navigate to the desired topic or position by tapping the document link annotation of the topics in the table of contents in a PDF document.
* **Themes** - Easily switch between light and dark themes.
* **Localization** - All static text within the PDF Viewer can be localized to any supported language.

Просмотреть файл

@ -1,81 +0,0 @@
---
layout: post
title: Accessibility in Flutter Range Selector widget | Syncfusion
description: Learn here all about the accessibility support in Syncfusion Flutter Range Selector (SfRangeSelector) widget.
platform: Flutter
control: SfRangeSelector
documentation: ug
---
# Accessibility in Flutter Range Selector (SfRangeSelector)
## Screen reader
The [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) can be accessed by screen readers. The default reading format for start thumb is `The start value is ${values.start}` and end thumb is `the end value is ${values.end}`. You can change the reading format using the [`semanticFormatterCallback`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/semanticFormatterCallback.html) property.
For android, you can adjust the value of each thumb by moving the focus to the thumb and then pressing the volume buttons to increase or decrease the value.
For iOS, you can adjust the value of each thumb by moving the focus to the thumb and then swiping up or down to increase or decrease the value respectively.
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(40.0, 60.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: 0.0,
max: 100.0,
initialValues: _values,
interval: 20,
showTicks: true,
showLabels: true,
semanticFormatterCallback: (dynamic value, SfThumb thumb){
return 'The $thumb value is $value';
},
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
child: Container(
height: 200,
color: Colors.pink[200],
),
),
)
),
);
}
{% endhighlight %}
{% endtabs %}
## Sufficient contrast
You can customize the color of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) elements using the following APIs for the sufficient contrast.
* [`Track`](https://help.syncfusion.com/flutter/range-selector/track#track-color)
* [`Major ticks`](https://help.syncfusion.com/flutter/range-selector/ticks#major-ticks-color)
* [`Minor ticks`](https://help.syncfusion.com/flutter/range-selector/ticks#minor-ticks-color)
* [`Labels`](https://help.syncfusion.com/flutter/range-selector/labels-and-divisor#label-style)
* [`Divisors`](https://help.syncfusion.com/flutter/range-selector/labels-and-divisor#divisor-color)
* [`Thumb`](https://help.syncfusion.com/flutter/range-selector/thumb-and-overlay#thumb-color)
* [`Thumb overlay`](https://help.syncfusion.com/flutter/range-selector/thumb-and-overlay#thumb-overlay-color)
* [`Active region color`](https://help.syncfusion.com/flutter/range-selector/basic-features#active-region-color)
* [`Inactive region color`](https://help.syncfusion.com/flutter/range-selector/basic-features#inactive-region-color)
## Large fonts
The font size of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) will be automatically scaled based on the device settings. Also, you can change the font size of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) elements using the following APIs:
* [`Label style`](https://help.syncfusion.com/flutter/range-selector/labels-and-divisor#label-style)
* [`Tooltip label style`](https://help.syncfusion.com/flutter/range-selector/tooltip#tooltip-label-style)
## Easier touch targets
The [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) has touch target as 48 * 48 as per the standard for all the elements.

Просмотреть файл

@ -1,542 +0,0 @@
---
layout: post
title: Basic features in Flutter Range Selector widget | Syncfusion
description: Learn here all about adding the Basic features in Syncfusion Flutter Range Selector (SfRangeSelector) widget and more.
platform: Flutter
control: SfRangeSelector
documentation: ug
---
# Basic features in Flutter Range Selector (SfRangeSelector)
This section explains about how to add the numeric and date range selector.
## Minimum
The minimum value that the user can select. The default value of [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) property is 0.0 and it must be less than the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) value.
## Maximum
The maximum value that the user can select. The default value of [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) property is 1.0 and it must be greater than the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) value.
## Initial values
It represents the initial values in the range selector. The range selector's thumb is drawn corresponding to this value.
N> For date values, the range selector does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateFormat.html) for date values.
**Numeric range selector**
You can show numeric values in the range selector by setting `double` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) and [`initialValues`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/initialValues.html) properties.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(5.0, 8.0);
final List<Data> _chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
showTicks: true,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: _chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Numeric range selector](images/basic-features/selector_numeric_label.png)
**Date range selector**
You can show date values in the range selector by setting `DateTime` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) and [`initialValues`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/initialValues.html) properties.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting date range selector using the [`DateFormat`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
{% tabs %}
{% highlight Dart %}
final DateTime _min = DateTime(2002, 01, 01);
final DateTime _max = DateTime(2010, 01, 01);
SfRangeValues _values = SfRangeValues(DateTime(2005, 01, 01), DateTime(2008, 01, 01));
final List<Data> _chartData = <Data>[
Data(x: DateTime(2002, 01, 01), y: 2.2),
Data(x: DateTime(2003, 01, 01), y: 3.4),
Data(x: DateTime(2004, 01, 01), y: 2.8),
Data(x: DateTime(2005, 01, 01), y: 1.6),
Data(x: DateTime(2006, 01, 01), y: 2.3),
Data(x: DateTime(2007, 01, 01), y: 2.5),
Data(x: DateTime(2008, 01, 01), y: 2.9),
Data(x: DateTime(2009, 01, 01), y: 3.8),
Data(x: DateTime(2010, 01, 01), y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
showLabels: true,
showTicks: true,
interval: 1,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: DateTimeAxis(
minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, DateTime>>[
SplineAreaSeries<Data, DateTime>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: _chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final DateTime x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Date range selector](images/basic-features/selector_date_label.png)
**Handle value change**
The [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/onChanged.html) callback is called when the user is selecting the new values.
{% tabs %}
{% highlight Dart %}
final SfRangeValues _initialValues = SfRangeValues(0.3, 0.7);
final List<Data> _chartData = <Data>[
Data(x: DateTime(2003, 01, 01), y: 3.4),
Data(x: DateTime(2004, 01, 01), y: 2.8),
Data(x: DateTime(2005, 01, 01), y: 1.6),
Data(x: DateTime(2006, 01, 01), y: 2.3),
Data(x: DateTime(2007, 01, 01), y: 2.5),
Data(x: DateTime(2008, 01, 01), y: 2.9),
Data(x: DateTime(2009, 01, 01), y: 3.8),
Data(x: DateTime(2010, 01, 01), y: 2.0),
];
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: SfRangeSelector(
initialValues: _initialValues,
onChanged: (SfRangeValues values) {
},
child: Container(
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: DateTimeAxis(
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false, maximum: 4),
series: <SplineAreaSeries<Data, DateTime>>[
SplineAreaSeries<Data, DateTime>(
dataSource: _chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
height: 250,
),
),
),
);
}
class Data {
Data({required this.x, required this.y});
final DateTime x;
final double y;
}
{% endhighlight %}
{% endtabs %}
## Active color
It represents the color applied to the active track, thumb, overlay, and inactive divisors.
The active side of the range selector is between start and end thumbs.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(4.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
showTicks: true,
activeColor: Color.fromARGB(255, 253, 125, 0),
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Active color support](images/basic-features/selector_active_color.png)
## Inactive color
It represents the color applied to the inactive track and active divisors.
The active side of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) is between start and end thumbs.
The inactive side of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) is between the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) value and the left thumb, and the right thumb and the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) value.
For RTL, the inactive side is between the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) value and the left thumb, and the right thumb and the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) value.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(4.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
showTicks: true,
activeColor: Color.fromARGB(255,5, 90, 194),
inactiveColor: Color.fromARGB(140, 121, 244, 195),
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Inactive color support](images/basic-features/selector_inactive_color.png)
## Active region color
It specifies the color for the active region of the child in the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html).
The active side of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) is between start and end thumbs.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(5.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelectorTheme(
data: SfRangeSelectorThemeData(
activeRegionColor: Colors.greenAccent[100],
),
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
showTicks: true,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Active region color support](images/basic-features/selector-active-region-color.png)
## Inactive region color
It specifies the color for the inactive region of the child in the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html).
The inactive side of the [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html) is between the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) value and the left thumb, and the right thumb and the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) value.
For RTL, the inactive side is between the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) value and the left thumb, and the right thumb and the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) value.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(4.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelectorTheme(
data: SfRangeSelectorThemeData(
inactiveRegionColor: Colors.greenAccent[100],
),
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
showTicks: true,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Inactive region color support](images/basic-features/selector-inactive-region-color.png)
### For customizing individual items
* Track - [`Link`](https://help.syncfusion.com/flutter/range-selector/track)
* Ticks - [`Link`](https://help.syncfusion.com/flutter/range-selector/ticks)
* Labels and divisors - [`Link`](https://help.syncfusion.com/flutter/range-selector/labels-and-divisor)
* Tooltips - [`Link`](https://help.syncfusion.com/flutter/range-selector/tooltip)
* Thumb and overlay - [`Link`](https://help.syncfusion.com/flutter/range-selector/thumb-and-overlay)

Просмотреть файл

@ -1,175 +0,0 @@
---
layout: post
title: Disabled state in Flutter Range Selector widget | Syncfusion
description: Learn here all about the Disabled state in Syncfusion Flutter Range Selector (SfRangeSelector) widget.
platform: Flutter
control: SfRangeSelector
documentation: ug
---
# Disabled state in Flutter Range Selector (SfRangeSelector)
This section helps to learn about the disabled state in the Flutter range selector.
## Disabled state
You can render the range selector in disabled state using [`enabled`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/enabled.html) property. The default value of [`enabled`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/enabled.html) property is `true`.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _initialValues = SfRangeValues(5.0, 8.0);
final List<Data> _chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
enabled: false,
initialValues: _initialValues,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: _chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Range selector disabled state](images/disabled-state/selector_disabled_state.png)
## Disabled color
You can change,
* The color of the active and inactive track in disabled state using the [`disabledActiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledActiveTrackColor.html) and [`disabledInactiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledInactiveTrackColor.html) properties.
* The color of the active and inactive major ticks in disabled state using the [`disabledActiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledActiveTickColor.html) and [`disabledInactiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledInactiveTickColor.html) properties.
* The color of the active and inactive minor ticks in disabled state using the [`disabledActiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledActiveMinorTickColor.html) and [`disabledInactiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledInactiveMinorTickColor.html) properties.
* The color of the active and inactive divisors in disabled state using the [`disabledActiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledActiveDivisorColor.html) and [`disabledInactiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledInactiveDivisorColor.html) properties.
* The color of the thumb in disabled state using the [`disabledThumbColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorThemeData/disabledThumbColor.html) property.
N> You must import the `theme.dart` library from the [`Core`](https://pub.dev/packages/syncfusion_flutter_core) package to use [`SfRangeSelectorTheme`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSelectorTheme-class.html).
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _initialValues = SfRangeValues(4.0, 8.0);
final List<Data> _chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelectorTheme(
data: SfRangeSelectorThemeData(
disabledActiveTrackColor: Colors.red[900],
disabledInactiveTrackColor: Colors.red[200],
disabledActiveTickColor: Colors.red[900],
disabledInactiveTickColor: Colors.red[200],
disabledActiveMinorTickColor: Colors.red[900],
disabledInactiveMinorTickColor: Colors.red[200],
disabledActiveDivisorColor: Colors.blue[900],
disabledInactiveDivisorColor: Colors.blue[200],
disabledThumbColor: Colors.red,
activeTrackHeight: 4,
inactiveTrackHeight: 4,
),
child: SfRangeSelector(
min: _min,
max: _max,
interval: 1,
showLabels: true,
enabled: false,
showTicks: true,
showDivisors: true,
initialValues: _initialValues,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: _chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Disabled color support](images/disabled-state/selector-disabled-color.png)

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 13 KiB

Просмотреть файл

@ -1,387 +0,0 @@
---
layout: post
title: Interval in Flutter Range Selector widget | Syncfusion
description: Learn here all about adding the Interval feature in Syncfusion Flutter Range Selector (SfRangeSelector) widget and more.
platform: Flutter
control: SfRangeSelector
documentation: ug
---
# Interval in Flutter Range Selector (SfRangeSelector)
This section explains about how to add the interval for numeric and date range selector.
## Numeric interval
Range selector elements like labels, ticks and divisors are rendered based on the [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html), [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) properties. The default value of the [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html) property is `null` and it must be greater than 0.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) is 2.0 and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) is 10.0 and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html) is 2.0, the range selector will render the labels, major ticks, and divisors at 2.0, 4.0 and so on.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(4.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
interval: 2,
showLabels: true,
showTicks: true,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <ColumnSeries<Data, double>>[
ColumnSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Numeric interval](images/interval/numeric_interval.png)
N>
* Refer the [`showDivisors`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/showDivisors.html) to know about the rendering of divisors at given interval.
* Refer the [`showTicks`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/showTicks.html) to know about the rendering of major ticks at given interval.
* Refer the [`showLabels`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/showLabels.html) to know about the rendering of labels at given interval.
## Date interval
The type of date interval. It can be years to seconds. It is mandatory for date [`SfRangeSelector`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector-class.html). The default value of [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateIntervalType.html) property is `null`.
For date values, the range selector does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateFormat.html) for date values.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) is `DateTime(2002, 01, 01)` and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) is `DateTime(2010, 01, 01)` and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/interval.html) is `2`, [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateIntervalType.html) is `DateIntervalType.years`, [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/dateFormat.html) is `DateFormat.y()` then the range selector will render the labels, major ticks, and divisors at 2002, 2004, 2006 and so on.
{% tabs %}
{% highlight Dart %}
final DateTime _min = DateTime(2002, 01, 01);
final DateTime _max = DateTime(2010, 01, 01);
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2008, 01, 01));
final List<Data> chartData = <Data>[
Data(x: DateTime(2002, 01, 01), y: 2.2),
Data(x: DateTime(2003, 01, 01), y: 3.4),
Data(x: DateTime(2004, 01, 01), y: 2.8),
Data(x: DateTime(2005, 01, 01), y: 1.6),
Data(x: DateTime(2006, 01, 01), y: 2.3),
Data(x: DateTime(2007, 01, 01), y: 2.5),
Data(x: DateTime(2008, 01, 01), y: 2.9),
Data(x: DateTime(2009, 01, 01), y: 3.8),
Data(x: DateTime(2010, 01, 01), y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
showLabels: true,
showTicks: true,
interval: 2,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: DateTimeAxis(
minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <ColumnSeries<Data, DateTime>>[
ColumnSeries<Data, DateTime>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final DateTime x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Date interval](images/interval/date_interval.png)
## Discrete selection for numeric values
You can move the thumb in discrete manner for numeric values using the [`stepSize`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/stepSize.html) property in the range selector.
{% tabs %}
{% highlight Dart %}
final double _min = 2.0;
final double _max = 10.0;
SfRangeValues _values = SfRangeValues(4.0, 8.0);
final List<Data> chartData = <Data>[
Data(x:2.0, y: 2.2),
Data(x:3.0, y: 3.4),
Data(x:4.0, y: 2.8),
Data(x:5.0, y: 1.6),
Data(x:6.0, y: 2.3),
Data(x:7.0, y: 2.5),
Data(x:8.0, y: 2.9),
Data(x:9.0, y: 3.8),
Data(x:10.0, y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
interval: 2,
stepSize: 1,
showLabels: true,
showTicks: true,
minorTicksPerInterval: 1,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: NumericAxis(minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, double>>[
SplineAreaSeries<Data, double>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final double x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Step size support](images/interval/selector-step-size-support.gif)
## Discrete selection for date values
You can move the thumb in discrete manner for date values based on the value provided in the [`stepDuration`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/stepDuration.html) property in the range selector.
For example, if [min](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/min.html) is DateTime(2015, 01, 01) and [max](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/max.html) is DateTime(2020, 01, 01) and [stepDuration](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/stepDuration.html) is SliderDuration(years: 1, months: 6),the range selector will move the thumbs at DateTime(2015, 01, 01), DateTime(2016, 07, 01), DateTime(2018, 01, 01),and DateTime(2019, 07, 01).
{% tabs %}
{% highlight Dart %}
final DateTime _min = DateTime(2002, 01, 01);
final DateTime _max = DateTime(2010, 01, 01);
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2008, 01, 01));
final List<Data> chartData = <Data>[
Data(x: DateTime(2002, 01, 01), y: 2.2),
Data(x: DateTime(2003, 01, 01), y: 3.4),
Data(x: DateTime(2004, 01, 01), y: 2.8),
Data(x: DateTime(2005, 01, 01), y: 1.6),
Data(x: DateTime(2006, 01, 01), y: 2.3),
Data(x: DateTime(2007, 01, 01), y: 2.5),
Data(x: DateTime(2008, 01, 01), y: 2.9),
Data(x: DateTime(2009, 01, 01), y: 3.8),
Data(x: DateTime(2010, 01, 01), y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
showLabels: true,
showTicks: true,
interval: 2,
stepDuration: SliderStepDuration(years: 2),
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: DateTimeAxis(
minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, DateTime>>[
SplineAreaSeries<Data, DateTime>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final DateTime x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Step duration support](images/interval/selector-step-duration-support.gif)
## Enable interval selection
You can select a particular interval by tapping when setting the [`enableIntervalSelection`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSelector/enableIntervalSelection.html) property as `true`. Both the thumbs will be moved to the current interval with animation.
{% tabs %}
{% highlight Dart %}
final DateTime _min = DateTime(2002, 01, 01);
final DateTime _max = DateTime(2010, 01, 01);
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2008, 01, 01));
final List<Data> chartData = <Data>[
Data(x: DateTime(2002, 01, 01), y: 2.2),
Data(x: DateTime(2003, 01, 01), y: 3.4),
Data(x: DateTime(2004, 01, 01), y: 2.8),
Data(x: DateTime(2005, 01, 01), y: 1.6),
Data(x: DateTime(2006, 01, 01), y: 2.3),
Data(x: DateTime(2007, 01, 01), y: 2.5),
Data(x: DateTime(2008, 01, 01), y: 2.9),
Data(x: DateTime(2009, 01, 01), y: 3.8),
Data(x: DateTime(2010, 01, 01), y: 3.7),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSelector(
min: _min,
max: _max,
showLabels: true,
showTicks: true,
interval: 2,
enableIntervalSelection: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
initialValues: _values,
child: Container(
height: 130,
child: SfCartesianChart(
margin: const EdgeInsets.all(0),
primaryXAxis: DateTimeAxis(
minimum: _min,
maximum: _max,
isVisible: false,),
primaryYAxis: NumericAxis(isVisible: false),
plotAreaBorderWidth: 0,
series: <SplineAreaSeries<Data, DateTime>>[
SplineAreaSeries<Data, DateTime>(
color: Color.fromARGB(255, 126, 184, 253),
dataSource: chartData,
xValueMapper: (Data sales, int index) => sales.x,
yValueMapper: (Data sales, int index) => sales.y)
],
),
),
),
)
)
);
}
class Data {
Data({required this.x, required this.y});
final DateTime x;
final double y;
}
{% endhighlight %}
{% endtabs %}
![Interval selection support](images/interval/selector-interval-selection-support.gif)

Просмотреть файл

@ -1,21 +1,21 @@
---
layout: post
title: About Flutter Range Selector widget | Syncfusion
description: Learn here all about the introduction of Syncfusion Flutter Range Selector (SfRangeSelector) widget, its features, and more.
platform: Flutter
title: Overview of Syncfusion Flutter Range Selector
description: Syncfusion flutter range selector provides a rich set of features such as support for numeric and date values, ticks, labels and tooltips.
platform: flutter
control: SfRangeSelector
documentation: ug
---
# Flutter range selector (SfRangeSelector) Overview
# Overview of Range Selector
Syncfusion Flutter Range Selector is a highly interactive UI control for for selecting a smaller range from a larger data set. It provides a rich set of features such as numeric and date values, labels, ticks, divisors, and tooltips. It also supports adding any type of widget as content.
Syncfusion flutter range selector provides a rich set of features such as support for numeric and date values, ticks, labels and tooltips.
![Range selector overview](images/overview/range-selector-overview.png)
## Features
* **Child support** - Add a child of any type inside the range selector. It is also possible to add [Charts](https://www.syncfusion.com/flutter-widgets/flutter-charts) widget. With the built-in integrations, the range selector is smart enough to handle features like segment selection and zooming in the chart based on the selected range in the range selector. Similar to the range slider, it also supports both numeric and date values.
* **Child support** - Add a child of any type inside the range selector. It is also possible to add [Charts](https://help.syncfusion.com/flutter/chart/getting-started) widget. With the built-in integrations, the range selector is smart enough to handle features like segment selection and zooming in the chart based on the selected range in the range selector. Similar to the range slider, it also supports both numeric and date values.
* **Numeric and date support** - Provides functionality for selecting numeric and date ranges. For the date range, support is provided up to the seconds interval.
* **Labels** - Render labels for the date and numeric ranges with the option to customize their format based on your requirements.
* **Ticks and divisors** - Provides the option to show ticks and divisors based on the interval. Also enables minor ticks to indicate the values between each interval. These options present the selected range in a more intuitive way for end users.

Просмотреть файл

@ -1,113 +0,0 @@
---
layout: post
title: Accessibility in Flutter Range Slider widget | Syncfusion
description: Learn here all about the accessibility support in Syncfusion Flutter Range Slider (SfRangeSlider) widget.
platform: Flutter
control: SfRangeSlider
documentation: ug
---
# Accessibility in Flutter Range Slider (SfRangeSlider)
## Screen reader
The [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html) can be accessed by screen readers. The default reading format for start thumb is `The start value is ${values.start}` and end thumb is `the end value is ${values.end}`. You can change the reading format using the [`semanticFormatterCallback`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/semanticFormatterCallback.html) property.
For android, you can adjust the value of each thumb by moving the focus to it and then pressing the volume buttons to increase or decrease the value.
For iOS, you can adjust the value of each thumb by moving the focus to it and then swiping up or down to increase or decrease the value respectively.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(40.0, 60.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 100.0,
values: _values,
interval: 20,
showTicks: true,
showLabels: true,
semanticFormatterCallback: (dynamic value, SfThumb thumb){
return 'The $thumb value is $value';
},
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
),
);
}
{% endhighlight %}
{% endtabs %}
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(40.0, 60.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 100.0,
values: _values,
interval: 20,
showTicks: true,
showLabels: true,
semanticFormatterCallback: (dynamic value, SfThumb thumb){
return 'The $thumb value is $value';
},
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
),
);
}
{% endhighlight %}
{% endtabs %}
## Sufficient contrast
You can customize the color of the [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html) elements using the following APIs for the sufficient contrast.
* [`Track`](https://help.syncfusion.com/flutter/range-slider/track#track-color)
* [`Major ticks`](https://help.syncfusion.com/flutter/range-slider/ticks#major-ticks-color)
* [`Minor ticks`](https://help.syncfusion.com/flutter/range-slider/ticks#minor-ticks-color)
* [`Labels`](https://help.syncfusion.com/flutter/range-slider/labels-and-divisor#label-style)
* [`Divisors`](https://help.syncfusion.com/flutter/range-slider/labels-and-divisor#divisor-color)
* [`Thumb`](https://help.syncfusion.com/flutter/range-slider/thumb-and-overlay#thumb-color)
* [`Thumb overlay`](https://help.syncfusion.com/flutter/range-slider/thumb-and-overlay#thumb-overlay-color)
## Large fonts
The font size of the [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html) will be automatically scaled based on the device settings. Also, you can change the font size of the [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html) elements using the following APIs:
* [`Label style`](https://help.syncfusion.com/flutter/range-slider/labels-and-divisor#label-style)
* [`Tooltip label style`](https://help.syncfusion.com/flutter/range-slider/tooltip#tooltip-label-style)
## Easily touch targets
The [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html) has touch target as 48 * 48 as per the standard for all the elements.

Просмотреть файл

@ -1,405 +0,0 @@
---
layout: post
title: Basic features in Flutter Range Slider widget | Syncfusion
description: Learn here all about adding the basic features in Syncfusion Flutter Range Slider (SfRangeSlider) widget and more.
platform: Flutter
control: SfRangeSlider
documentation: ug
---
# Basic features in Flutter Range Slider (SfRangeSlider)
This section explains about how to add the numeric and date range slider.
## Minimum
The minimum value that the user can select. The default value of [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) property is 0.0 and it must be less than the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) value.
## Maximum
The maximum value that the user can select. The default value of [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) property is 1.0 and it must be greater than the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) value.
## Values
It represents the values currently selected in the range slider. The range slider's thumb is drawn corresponding to this value.
For date values, the range slider does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateFormat.html) for date values.
**Numeric range slider**
You can show numeric values in the range slider by setting `double` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) and [`values`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/values.html) properties.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
interval: 2,
showLabels: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric range slider](images/basic-features/numeric-labels.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
interval: 2,
showLabels: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric range slider](images/basic-features/vertical-numeric-labels.png)
**Date range slider**
You can show date values in the range slider by setting `DateTime` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) and [`values`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/values.html) properties.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting date range slider using the [`DateFormat`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2002, 01, 01), DateTime(2004, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
values: _values,
interval: 1,
showLabels: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date range slider](images/basic-features/date-labels.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2002, 01, 01), DateTime(2004, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
values: _values,
interval: 1,
showLabels: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date range slider](images/basic-features/vertical-date-labels.png)
**Handle value change**
The [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/onChanged.html) callback is called when the user selects a value through interaction.
N> The range slider passes the new values to the callback but does not change its state until the parent widget rebuilds the range slider with new values.
N> If it is null, the range slider will be disabled.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled range slider](images/basic-features/enabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled range slider](images/basic-features/vertical-enabled-state.png)
## Active color
It represents the color applied to the active track, thumb, overlay, and inactive divisors. The active side of the range slider is between the start and end thumbs.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
activeColor: Colors.red,
showDivisors: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Active color support](images/basic-features/active-color.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
activeColor: Colors.red,
showDivisors: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Active color support](images/basic-features/vertical-active-color.png)
## Inactive color
It represents the color applied to the inactive track and active divisors.
The inactive side of the range slider is between the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) value and the left thumb, and the right thumb and the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) value.
For RTL, the inactive side is between the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) value and the left thumb, and the right thumb and the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) value.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
activeColor: Colors.red,
inactiveColor: Colors.red.withOpacity(0.2),
showDivisors: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Inactive color support](images/basic-features/inactive-color.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
activeColor: Colors.red,
inactiveColor: Colors.red.withOpacity(0.2),
showDivisors: true,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Inactive color support](images/basic-features/vertical-inactive-color.png)
### For customizing individual items
* Track - [`Link`](https://help.syncfusion.com/flutter/range-slider/track)
* Ticks - [`Link`](https://help.syncfusion.com/flutter/range-slider/ticks)
* Labels and divisors - [`Link`](https://help.syncfusion.com/flutter/range-slider/labels-and-divisor)
* Tooltips - [`Link`](https://help.syncfusion.com/flutter/range-slider/tooltip)
* Thumb and overlay - [`Link`](https://help.syncfusion.com/flutter/range-slider/thumb-and-overlay)

Просмотреть файл

@ -1,238 +0,0 @@
---
layout: post
title: Enable & disable states in Flutter Range Slider widget | Syncfusion
description: Learn here all about enable & disable states in Syncfusion Flutter Range Slider (SfRangeSlider) widget and more.
platform: Flutter
control: SfRangeSlider
documentation: ug
---
# Enabled and disabled states in Flutter Range Slider (SfRangeSlider)
This section helps to learn about the enabled and disabled state in the Flutter range slider.
## Enabled state
The range slider will be in enabled state if [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/onChanged.html) is set.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled state](images/enabled-and-disabled/enabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled state](images/enabled-and-disabled/vertical-enabled-state.png)
## Disabled state
The range slider will be in disabled state if [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/onChanged.html) is `null`.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
values: _values,
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled range slider](images/enabled-and-disabled/disabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(3.0, 7.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
values: _values,
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled range slider](images/enabled-and-disabled/vertical-disabled-state.png)
## Disabled color
You can change,
* The color of the active and inactive track in disabled state using the [`disabledActiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledActiveTrackColor.html) and [`disabledInactiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledInactiveTrackColor.html) properties.
* The color of the active and inactive major ticks in disabled state using the [`disabledActiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledActiveTickColor.html) and [`disabledInactiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledInactiveTickColor.html) properties.
* The color of the active and inactive minor ticks in disabled state using the [`disabledActiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledActiveMinorTickColor.html) and [`disabledInactiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledInactiveMinorTickColor.html) properties.
* The color of the active and inactive divisors in disabled state using the [`disabledActiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledActiveDivisorColor.html) and [`disabledInactiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledInactiveDivisorColor.html) properties.
* The color of the thumb in disabled state using the [`disabledThumbColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData/disabledThumbColor.html) property.
N> You must import the `theme.dart` library from the [`Core`](https://pub.dev/packages/syncfusion_flutter_core) package to use [`SfRangeSliderTheme`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderTheme-class.html).
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 8.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSliderTheme(
data: SfRangeSliderThemeData(
disabledActiveTrackColor: Colors.orange,
disabledInactiveTrackColor: Colors.orange[200],
disabledActiveTickColor: Colors.orange,
disabledInactiveTickColor: Colors.orange[200],
disabledActiveMinorTickColor: Colors.orange,
disabledInactiveMinorTickColor: Colors.orange[200],
disabledActiveDivisorColor: Colors.purple,
disabledInactiveDivisorColor: Colors.purple[200],
disabledThumbColor: Colors.orange,
),
child: SfRangeSlider(
min: 2.0,
max: 10.0,
interval: 2,
showTicks: true,
minorTicksPerInterval: 1,
showDivisors: true,
values: _values,
),
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled color support](images/enabled-and-disabled/slider-disabled-color.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 8.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSliderTheme(
data: SfRangeSliderThemeData(
disabledActiveTrackColor: Colors.orange,
disabledInactiveTrackColor: Colors.orange[200],
disabledActiveTickColor: Colors.orange,
disabledInactiveTickColor: Colors.orange[200],
disabledActiveMinorTickColor: Colors.orange,
disabledInactiveMinorTickColor: Colors.orange[200],
disabledActiveDivisorColor: Colors.purple,
disabledInactiveDivisorColor: Colors.purple[200],
disabledThumbColor: Colors.orange,
),
child: SfRangeSlider.vertical(
min: 2.0,
max: 10.0,
interval: 2,
showTicks: true,
minorTicksPerInterval: 1,
showDivisors: true,
values: _values,
),
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled color support](images/enabled-and-disabled/vertical-slider-disabled-color.png)

Просмотреть файл

@ -1,410 +0,0 @@
---
layout: post
title: Interval in Flutter Range Slider widget | Syncfusion
description: Learn here all about adding the Interval feature in Syncfusion Flutter Range Slider (SfRangeSlider) widget and more.
platform: Flutter
control: SfRangeSlider
documentation: ug
---
# Interval in Flutter Range Slider (SfRangeSlider)
This section explains about how to add the interval for numeric and date range slider.
## Numeric interval
Range slider elements like labels, ticks and divisors are rendered based on the [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/interval.html), [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) properties. The default value is `null` and it must be greater than 0.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) is 0.0 and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) is 10.0 and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/interval.html) is 2.0, the range slider will render the labels, major ticks, and divisors at 0.0, 2.0, 4.0 and so on.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 6.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
interval: 2,
showTicks: true,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric interval support](images/interval/numeric-interval.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 6.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
interval: 2,
showTicks: true,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric interval support](images/interval/vertical-numeric-interval.png)
N>
* Refer the [`showDivisors`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/showDivisors.html) to know about the rendering of divisors at given interval.
* Refer the [`showTicks`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/showTicks.html) to know about the rendering of major ticks at given interval.
* Refer the [`showLabels`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/showLabels.html) to know about the rendering of labels at given interval.
## Date interval
The type of date interval. It can be years to seconds. It is mandatory for date [`SfRangeSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider-class.html). The default value of [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateIntervalType.html) property is `null`.
For date values, the range slider does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateFormat.html) for date values.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) is `DateTime(2000, 01, 01)` and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) is `DateTime(2005, 01, 01)` and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/interval.html) is `1`, [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateIntervalType.html) is `DateIntervalType.years`, [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/dateFormat.html) is `DateFormat.y()` then the range slider will render the labels, major ticks, and divisors at 2000, 2001, 2002 and so on.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2002, 01, 01), DateTime(2003, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
values: _values,
interval: 1,
showLabels: true,
showTicks: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date interval type support](images/interval/date-interval-type.png)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2002, 01, 01), DateTime(2003, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
values: _values,
interval: 1,
showLabels: true,
showTicks: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date interval type support](images/interval/vertical-date-interval-type.png)
## Discrete selection for numeric values
You can move the thumb in discrete manner for numeric values using the [`stepSize`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/stepSize.html) property in the range slider.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 6.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: 0.0,
max: 10.0,
interval: 2,
stepSize: 2,
showTicks: true,
minorTicksPerInterval: 1,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Step size support](images/interval/step-size-support.gif)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(4.0, 6.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: 0.0,
max: 10.0,
interval: 2,
stepSize: 2,
showTicks: true,
minorTicksPerInterval: 1,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
## Discrete selection for date values
You can move the thumb in discrete manner for date values based on the value provided in the [`stepDuration`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/stepDuration.html) property in the range slider.
For example, if [min](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/min.html) is DateTime(2015, 01, 01) and [max](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/max.html) is DateTime(2020, 01, 01) and [stepDuration](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/stepDuration.html) is SliderDuration(years: 1, months: 6),the range slider will move the thumbs at DateTime(2015, 01, 01), DateTime(2016, 07, 01), DateTime(2018, 01, 01),and DateTime(2019, 07, 01).
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2006, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
stepDuration: SliderStepDuration(years: 2),
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Step duration support](images/interval/range-step-duration-support.gif)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2006, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
stepDuration: SliderStepDuration(years: 2),
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
## Enable interval selection
You can select a particular interval by tapping when setting the [`enableIntervalSelection`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfRangeSlider/enableIntervalSelection.html) property as `true`. Both the thumbs will be moved to the current interval with animation.
### Horizontal
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2006, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
enableIntervalSelection: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
enableTooltip: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Interval selection support](images/interval/range-interval-selection-support.gif)
### Vertical
{% tabs %}
{% highlight Dart %}
SfRangeValues _values = SfRangeValues(DateTime(2004, 01, 01), DateTime(2006, 01, 01));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfRangeSlider.vertical(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
enableIntervalSelection: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
enableTooltip: true,
values: _values,
onChanged: (SfRangeValues newValues) {
setState(() {
_values = newValues;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,15 +1,15 @@
---
layout: post
title: About Flutter Range Slider widget | Syncfusion
description: Learn here all about the introduction of Syncfusion Flutter Range Slider (SfRangeSlider) widget, its features, and more.
platform: Flutter
title: Overview of Syncfusion Flutter Range Slider
description: Syncfusion flutter range slider provides a rich set of features such as support for numeric and date values, tooltips, labels, and ticks.
platform: flutter
control: SfRangeSlider
documentation: ug
---
# Flutter range slider (SfRangeSlider) Overview
# Overview of Range Slider
Syncfusion Flutter Range Slider is a highly interactive UI control, allowing users to select a smaller range from a larger data set. It provides rich features, such as numeric and date values, labels, ticks, divisors, and tooltips.
Syncfusion flutter range slider provides a rich set of features such as support for numeric and date values, tooltips, labels, and ticks.
![Range slider overview](images/overview/range-slider-overview.png)
@ -20,4 +20,3 @@ Syncfusion Flutter Range Slider is a highly interactive UI control, allowing use
* **Ticks and divisors** - Provides the option to show ticks and divisors based on the interval. Also enables minor ticks to indicate the values between each interval. These options present the selected range in a more intuitive way for end users.
* **Highly customizable** - In addition to the rich set of built-in features, fully customize the control in a much simpler way using the wide range of provided options.
* **Tooltips** - Render tooltips to show the selected range clearly. It is also possible to customize the format of the text shown in the tooltip.
* **Orientation** - Supports both horizontal and vertical orientations.

Просмотреть файл

@ -1,317 +0,0 @@
---
layout: post
title: Getting started with Flutter Signature Pad widget | Syncfusion
description: Learn here about getting started with Syncfusion Flutter Signature Pad (SfSignaturePad) widget, its elements, and more.
platform: Flutter
control: SfSignaturePad
documentation: ug
---
# Getting Started with Flutter SignaturePad (SfSignaturePad)
This section explains the steps required to add the SignaturePad widget and its elements such as minimum and maximum stroke widths, stroke color and background color. This section also covers how to save the signature as image, clear the existing signature in SignaturePad and handle the [`onSignStart`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/onSignStart.html) and [`onSignEnd`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/onSignEnd.html) callbacks in the SignaturePad widget.
## Add Flutter SignaturePad to an application
Create a simple project using the instructions given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter SignaturePad dependency to your pubspec.yaml file.
{% highlight dart %}
dependencies:
syncfusion_flutter_signaturepad: ^xx.x.xx
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of [`Syncfusion Flutter SignaturePad`](https://pub.dev/packages/syncfusion_flutter_signaturepad) package.
**Get packages**
Run the following command to get the required packages.
{% highlight dart %}
$ flutter pub get
{% endhighlight %}
**Import package**
Import the following package in your Dart code.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_signaturepad/signaturepad.dart';
{% endhighlight %}
{% endtabs %}
## Initialize SignaturePad
After importing the package, initialize the SignaturePad widget as a child of any widget. Here, the SignaturePad widget is added as a child of the Container widget to get a position and size. Also, applied a background color to show the SignaturePad widget in white background.The default [`backgroundColor`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/backgroundColor.html) is `Colors.transparent`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfSignaturePad(
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
),
);
}
{% endhighlight %}
{% endtabs %}
![Flutter SignaturePad](images/getting-started/blank_signature_pad.PNG)
## Customize signature stroke color
You can customize the stroke color of the SignaturePad widget by using the [`strokeColor`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/strokeColor.html) property. The default stroke color for the dark theme is `Colors.white` and the default color for the light theme is `Colors.black`.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfSignaturePad(
strokeColor: Colors.green,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
),
);
}
{% endhighlight %}
{% endtabs %}
## Customize signature stroke width
The width of the signature stroke can be customized by setting the [`minimumStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/minimumStrokeWidth.html) and [`maximumStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/maximumStrokeWidth.html) properties. The [`minimumStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/minimumStrokeWidth.html) defines the minimum thickness of the stroke and the [`maximumStrokeWidth`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/maximumStrokeWidth.html) defines the maximum thickness of the signature stroke. The stroke will be drawn in [`SfSignaturePad`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/SfSignaturePad.html) based on the speed of the stroke gesture within its minimum and maximum stroke width ranges. So that the signature will be more realistic.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfSignaturePad(
minimumStrokeWidth: 3.0,
maximumStrokeWidth: 6.0,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
),
);
}
{% endhighlight %}
{% endtabs %}
## Save signatures as images in Mobile and Desktop platforms
You can save the signature drawn in the SignaturePad as an image using the [`toImage()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/toImage.html) method as shown in the below code example in Android, iOS and Desktop platforms. Since this [`toImage()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/toImage.html) method is defined in the state object of SignaturePad, you have to use a global key assigned to the SignaturePad instance to call this method. Optionally, the `pixelRatio` parameter may be used to set the pixel ratio of the image. The higher the pixel ratio value, the high-quality picture you get. The default value of the pixel ratio parameter is 1.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
GlobalKey<SfSignaturePadState> _signaturePadKey = GlobalKey();
return Scaffold(
body: Column(
children: [
Container(
child: SfSignaturePad(
key: _signaturePadKey,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
RaisedButton(
child: Text("Save As Image"),
onPressed: () async {
ui.Image image =
await _signaturePadKey.currentState!.toImage();
}),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Save signatures as images in web (Desktop browser)
This is similar to the mobile and desktop platforms. You can save the signature drawn in the SignaturePad as an image using the [`toImage()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/toImage.html) method as shown in the below code example in web platform (Desktop browser). Since this [`toImage()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/toImage.html) method is defined in the state object of SignaturePad, you have to use a global key assigned to the SignaturePad instance to call this method. Optionally, the `pixelRatio` parameter may be used to set the pixel ratio of the image. The higher the pixel ratio value, the high-quality picture you get. The default value of the pixel ratio parameter is 1.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
GlobalKey<SfSignaturePadState> _signaturePadKey = GlobalKey();
return Scaffold(
body: Column(
children: [
Container(
child: SfSignaturePad(
key: _signaturePadKey,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
RaisedButton(
child: Text("Save As Image"),
onPressed: () async {
ui.Image image =
await _signaturePadKey.currentState!.toImage();
}),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Save signatures as images in web (mobile browser)
You can save the signature drawn in the SignaturePad as an image using the [`renderToContext2D`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/renderToContext2D.html) method as show in the below code snippet. Since this [`renderToContext2D()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/renderToContext2D.html) method is defined in the state object of SignaturePad, you have to use a global key assigned to the SignaturePad instance to call this method.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
GlobalKey<SfSignaturePadState> _signaturePadKey = GlobalKey();
return Scaffold(
body: Column(
children: [
Container(
child: SfSignaturePad(
key: _signaturePadKey,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
RaisedButton(
child: Text("Save As Image"),
onPressed: () async {
//Get a html canvas context.
final canvas = html.CanvasElement(width: 500, height: 500);
final context = canvas.context2D;
//Get the signature in the canvas context.
_signaturePadKey.currentState!.renderToContext2D(context);
//Get the image from the canvas context
final blob = await canvas.toBlob('image/jpeg', 1.0);
//Save the image as Uint8List to use it in local device.
final completer = Completer<Uint8List>();
final reader = html.FileReader();
reader.readAsArrayBuffer(blob);
reader.onLoad.listen((_) => completer.complete(reader.result));
Uint8List imageData = await completer.future;
}),
],
),
);
}
{% endhighlight %}
{% endtabs %}
N> Since Flutter uses two separate default web renderers, here we have two different code snippets to convert signatures to images in desktop and mobile browsers. Please refer to this Flutter [`web-renderers`](https://flutter.dev/docs/development/tools/web-renderers) page for more details.
## Clear the existing signature in SignaturePad
You can clear the signature drawn in the SignaturePad using the [`clear()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/clear.html) method as show in the below code snippet. Since this [`clear()`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePadState/clear.html) method is defined in the state object of SignaturePad, you have to use a global key assigned to the SignaturePad instance to call this method.
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
GlobalKey<SfSignaturePadState> _signaturePadKey = GlobalKey();
return Scaffold(
body: Column(
children: [
Container(
child: SfSignaturePad(
key: _signaturePadKey,
backgroundColor: Colors.grey[200],
),
height: 200,
width: 300,
),
RaisedButton(
child: Text("Save As Image"),
onPressed: () async {
ui.Image image =
_signaturePadKey.currentState!.clear();
}),
],
),
);
}
{% endhighlight %}
{% endtabs %}
## Handle onSignStart and onSignEnd callbacks
The widget allows to handle the onSignStart and onSignEnd callbacks for every strokes updated to the SignaturePad.The [`onSignStart`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/onSignStart.html) callback will be called when the user starts signing on `SfSignaturePad`and the [`onSignEnd`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/onSignEnd.html) callback will be called when the user completes signing on [`SfSignaturePad`](https://pub.dev/documentation/syncfusion_flutter_signaturepad/latest/signaturepad/SfSignaturePad/SfSignaturePad.html).
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SfSignaturePad(
backgroundColor: Colors.grey[200],
onSignStart: ()=> {
print("Signature has been initiated in SignaturePad");
},
onSignEnd: ()=> {
print("Signature has been completed in SignaturePad");
},
),
height: 200,
width: 300,
),
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,113 +0,0 @@
---
layout: post
title: Accessibility in Flutter Slider widget | Syncfusion
description: Learn here all about the accessibility support in Syncfusion Flutter Slider (SfSlider) widget and how to customize the text.
platform: Flutter
control: SfSlider
documentation: ug
---
# Accessibility in Flutter Slider (SfSlider)
## Screen reader
The [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html) can be accessed by screen readers. By default, it will read the current value. You can change the reading format using the [`semanticFormatterCallback`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/semanticFormatterCallback.html) property.
For android, you can adjust the value of thumb by moving the focus to it and then pressing the volume buttons to increase or decrease the value.
For iOS, you can adjust the value of thumb by moving the focus to it and then swiping up or down to increase or decrease the value respectively.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 40.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 100.0,
value: _value,
interval: 20,
showTicks: true,
showLabels: true,
semanticFormatterCallback: (dynamic value){
return 'The selected value is $value';
},
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
),
);
}
{% endhighlight %}
{% endtabs %}
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 40.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 100.0,
value: _value,
interval: 20,
showTicks: true,
showLabels: true,
semanticFormatterCallback: (dynamic value){
return 'The selected value is $value';
},
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
),
);
}
{% endhighlight %}
{% endtabs %}
## Sufficient contrast
You can customize the color of the [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html) elements using the following APIs for the sufficient contrast.
* [`Track`](https://help.syncfusion.com/flutter/slider/track#track-color)
* [`Major ticks`](https://help.syncfusion.com/flutter/slider/ticks#major-ticks-color)
* [`Minor ticks`](https://help.syncfusion.com/flutter/slider/ticks#minor-ticks-color)
* [`Labels`](https://help.syncfusion.com/flutter/slider/labels-and-divisor#label-style)
* [`Divisors`](https://help.syncfusion.com/flutter/slider/labels-and-divisor#divisor-color)
* [`Thumb`](https://help.syncfusion.com/flutter/slider/thumb-and-overlay#thumb-color)
* [`Thumb overlay`](https://help.syncfusion.com/flutter/slider/thumb-and-overlay#thumb-overlay-color)
## Large fonts
The font size of the [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html) will be automatically scaled based on the device settings. Also, you can change the font size of the [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html) elements using the following APIs:
* [`Label style`](https://help.syncfusion.com/flutter/slider/labels-and-divisor#label-style)
* [`Tooltip label style`](https://help.syncfusion.com/flutter/slider/tooltip#tooltip-label-style)
## Easier touch targets
The [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html) has touch target as 48 * 48 as per the standard for all the elements.

Просмотреть файл

@ -1,415 +0,0 @@
---
layout: post
title: Basic features in Flutter Slider widget | Syncfusion
description: Learn here all about adding the Basic feature of Syncfusion Flutter Slider (SfSlider) widget and more.
platform: Flutter
control: SfSlider
documentation: ug
---
# Basic features in Flutter Slider (SfSlider)
This section explains about how to add the numeric and date slider.
## Minimum
The minimum value that the user can select. The default value of [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) property is 0.0 and it must be less than the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) value.
## Maximum
The maximum value that the user can select. The default value of [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) property is 1.0 and it must be greater than the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) value.
## Value
It represents the value currently selected in the slider. The slider's thumb is drawn corresponding to this value.
For date values, the slider does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateFormat.html) for date values.
**Numeric slider**
You can show numeric values in the slider by setting `double` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) and [`value`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/value.html) properties.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric slider](images/basic-features/numeric-labels.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric slider](images/basic-features/vertical_numeric_labels.png)
**Date slider**
You can show date values in the slider by setting `DateTime` values to the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html), [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) and [`value`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/value.html) properties.
N> You must import [`intl`](https://pub.dev/packages/intl) package for formatting date slider using the [`DateFormat`](https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html) class.
### Horizontal
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2002, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
value: _value,
interval: 1,
showLabels: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date slider](images/basic-features/date-labels.png)
### Vertical
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2002, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
value: _value,
interval: 1,
showLabels: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date slider](images/basic-features/vertical_date_labels.png)
**Handle value change**
The [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/onChanged.html) callback is called when the user selects a value through interaction.
N> The slider passes the new value to the callback but does not change its state until the parent widget rebuilds the slider with new value.
N> If it is null, the slider will be disabled.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enable slider](images/basic-features/enabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enable slider](images/basic-features/vertical_enabled_state.png)
## Active color
It represents the color applied to the active track, thumb, overlay, and inactive divisors. The active side of the slider is between the [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) value and the thumb.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
activeColor: Colors.red,
showDivisors: true,
showTicks: true,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Active color support](images/basic-features/active-color.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
activeColor: Colors.red,
showDivisors: true,
showTicks: true,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Active color support](images/basic-features/vertical_active_color.png)
## Inactive color
It represents the color applied to the inactive track and active divisors.
The inactive side of the slider is between the thumb and the [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) value.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
activeColor: Colors.red,
inactiveColor: Colors.red.withOpacity(0.2),
showDivisors: true,
showTicks: true,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Inactive color support](images/basic-features/inactive-color.png)
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: _value,
interval: 2,
activeColor: Colors.red,
inactiveColor: Colors.red.withOpacity(0.2),
showDivisors: true,
showTicks: true,
showLabels: true,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Inactive color support](images/basic-features/vertical_inactive_color.png)
### For customizing individual items
* Track - [`Link`](https://help.syncfusion.com/flutter/slider/track)
* Ticks - [`Link`](https://help.syncfusion.com/flutter/slider/ticks)
* Labels and divisors - [`Link`](https://help.syncfusion.com/flutter/slider/labels-and-divisor)
* Tooltip - [`Link`](https://help.syncfusion.com/flutter/slider/tooltip)
* Thumb and overlay - [`Link`](https://help.syncfusion.com/flutter/slider/thumb-and-overlay)

Просмотреть файл

@ -1,236 +0,0 @@
---
layout: post
title: Enable & disable states in Flutter Slider widget | Syncfusion
description: Learn here all about the enabled and disabled states of the Syncfusion Flutter Slider (SfSlider) widget and how to customize them.
platform: Flutter
control: SfSlider
documentation: ug
---
# Enabled and disabled states in Flutter Slider (SfSlider)
This section helps to learn about the enabled and disabled state in the Flutter slider.
## Enabled state
The slider will be in enabled state if [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/onChanged.html) is set.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 5.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled state](images/enabled-and-disabled/enabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 5.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Enabled state](images/enabled-and-disabled/vertical-enabled-state.png)
## Disabled state
The slider will be in disabled state if [`onChanged`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/onChanged.html) is `null`.
### Horizontal
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
value: 5.0,
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled slider](images/enabled-and-disabled/disabled-state.png)
### Vertical
{% tabs %}
{% highlight Dart %}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
value: 5.0,
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled slider](images/enabled-and-disabled/vertical-disabled-state.png)
## Disabled color
You can change,
* The color of the active and inactive track in disabled state using the [`disabledActiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledActiveTrackColor.html) and [`disabledInactiveTrackColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledInactiveTrackColor.html) properties.
* The color of the active and inactive major ticks in disabled state using the [`disabledActiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledActiveTickColor.html) and [`disabledInactiveTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledInactiveTickColor.html) properties.
* The color of the active and inactive minor ticks in disabled state using the [`disabledActiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledActiveMinorTickColor.html) and [`disabledInactiveMinorTickColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledInactiveMinorTickColor.html) properties.
* The color of the active and inactive divisors in disabled state using the [`disabledActiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledActiveDivisorColor.html) and [`disabledInactiveDivisorColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledInactiveDivisorColor.html) properties.
* The color of the thumb in disabled state using the [`disabledThumbColor`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData/disabledThumbColor.html) property.
N> You must import the `theme.dart` library from the [`Core`](https://pub.dev/packages/syncfusion_flutter_core) package to use [`SfSliderTheme`](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderTheme-class.html).
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 6.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSliderTheme(
data: SfSliderThemeData(
disabledActiveTrackColor: Colors.orange,
disabledInactiveTrackColor: Colors.orange[200],
disabledActiveTickColor: Colors.orange,
disabledInactiveTickColor: Colors.orange[200],
disabledActiveMinorTickColor: Colors.orange,
disabledInactiveMinorTickColor: Colors.orange[200],
disabledActiveDivisorColor: Colors.purple,
disabledInactiveDivisorColor: Colors.purple[200],
disabledThumbColor: Colors.orange,
),
child: SfSlider(
min: 2.0,
max: 10.0,
interval: 2,
showTicks: true,
minorTicksPerInterval: 1,
showDivisors: true,
value: _value,
),
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled color support](images/enabled-and-disabled/slider-disabled-color.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 6.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSliderTheme(
data: SfSliderThemeData(
disabledActiveTrackColor: Colors.orange,
disabledInactiveTrackColor: Colors.orange[200],
disabledActiveTickColor: Colors.orange,
disabledInactiveTickColor: Colors.orange[200],
disabledActiveMinorTickColor: Colors.orange,
disabledInactiveMinorTickColor: Colors.orange[200],
disabledActiveDivisorColor: Colors.purple,
disabledInactiveDivisorColor: Colors.purple[200],
disabledThumbColor: Colors.orange,
),
child: SfSlider.vertical(
min: 2.0,
max: 10.0,
interval: 2,
showTicks: true,
minorTicksPerInterval: 1,
showDivisors: true,
value: _value,
),
)
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Disabled color support](images/enabled-and-disabled/vertical-slider-disabled-color.png)

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 4.2 KiB

Просмотреть файл

@ -1,331 +0,0 @@
---
layout: post
title: Interval in Flutter Slider widget | Syncfusion
description: Learn here all about adding the Interval feature of Syncfusion Flutter Slider (SfSlider) widget and more.
platform: Flutter
control: SfSlider
documentation: ug
---
# Interval in Flutter Slider (SfSlider)
This section explains about how to add the interval for numeric and date slider.
## Numeric interval
Slider elements like labels, ticks and divisors are rendered based on the [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/interval.html), [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) properties. The default value is `null` and it must be greater than 0.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) is 0.0 and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) is 10.0 and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/interval.html) is 2.0, the slider will render the labels, major ticks, and divisors at 0.0, 2.0, 4.0 and so on.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
interval: 2,
showTicks: true,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric interval support](images/interval/numeric-interval.png)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
interval: 2,
showTicks: true,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Numeric interval support](images/interval/vertical-numeric-interval.png)
N>
* Refer the [`showDivisors`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/showDivisors.html) to know about the rendering of divisors at given interval.
* Refer the [`showTicks`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/showTicks.html) to know about the rendering of major ticks at given interval.
* Refer the [`showLabels`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/showLabels.html) to know about the rendering of labels at given interval.
## Date interval
The type of date interval. It can be years to seconds. It is mandatory for date [`SfSlider`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider-class.html). The default value of [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateIntervalType.html) property is `null`.
For date values, the slider does not have auto interval support. So, it is mandatory to set [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/interval.html), [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateIntervalType.html), and [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateFormat.html) for date values.
For example, if [`min`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) is `DateTime(2000, 01, 01)` and [`max`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) is `DateTime(2005, 01, 01)` and [`interval`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/interval.html) is `1`, [`dateIntervalType`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateIntervalType.html) is `DateIntervalType.years`, [`dateFormat`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/dateFormat.html) is `DateFormat.y()` then the slider will render the labels, major ticks, and divisors at 2000, 2001, 2002 and so on.
### Horizontal
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2002, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
value: _value,
interval: 1,
showLabels: true,
showTicks: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date interval type support](images/interval/date-interval-type.png)
### Vertical
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2002, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: DateTime(2000, 01, 01, 00),
max: DateTime(2004, 12, 31, 24),
value: _value,
interval: 1,
showLabels: true,
showTicks: true,
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Date interval type support](images/interval/vertical-date-interval-type.png)
## Discrete selection for numeric values
You can move the thumb in discrete manner for numeric values using the [`stepSize`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/stepSize.html) property in the slider.
### Horizontal
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: 0.0,
max: 10.0,
interval: 2,
stepSize: 2,
showTicks: true,
minorTicksPerInterval: 1,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Step size support](images/interval/step-size-support.gif)
### Vertical
{% tabs %}
{% highlight Dart %}
double _value = 4.0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: 0.0,
max: 10.0,
interval: 2,
stepSize: 2,
showTicks: true,
minorTicksPerInterval: 1,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
## Discrete selection for date values
You can move the thumb in discrete manner for date values using the [`stepDuration`](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/stepDuration.html) property in the slider.
For example, if [min](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/min.html) is DateTime(2015, 01, 01) and [max](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/max.html) is DateTime(2020, 01, 01) and [stepDuration](https://pub.dev/documentation/syncfusion_flutter_sliders/latest/sliders/SfSlider/stepDuration.html) is SliderDuration(years: 1, months: 6),the slider will move the thumbs at DateTime(2015, 01, 01), DateTime(2016, 07, 01), DateTime(2018, 01, 01),and DateTime(2019, 07, 01).
### Horizontal
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2004, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
stepDuration: SliderStepDuration(years: 2),
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}
![Step duration support](images/interval/step-duration-support.gif)
### Vertical
{% tabs %}
{% highlight Dart %}
DateTime _value = DateTime(2004, 01, 01);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SfSlider.vertical(
min: DateTime(2000, 01, 01),
max: DateTime(2010, 01, 01),
interval: 2,
stepDuration: SliderStepDuration(years: 2),
dateFormat: DateFormat.y(),
dateIntervalType: DateIntervalType.years,
showTicks: true,
showLabels: true,
value: _value,
onChanged: (dynamic newValue) {
setState(() {
_value = newValue;
});
},
),
)
)
);
}
{% endhighlight %}
{% endtabs %}

Просмотреть файл

@ -1,30 +0,0 @@
---
layout: post
title: About Flutter Slider widget | Syncfusion
description: Learn here all about the introduction of Syncfusion Flutter Slider (SfSlider) widget, its features, and more.
platform: Flutter
control: SfSlider
documentation: ug
---
# Flutter Slider (SfSlider) Overview
Syncfusion Flutter Slider is a highly interactive UI control, allowing users to select a single value from a range of values. It provides rich features, such as numeric and date values, labels, ticks, divisors, and tooltip.
![Slider overview](images/overview/slider-overview.png)
## Features
* **Numeric and date support** - Provides functionality for selecting numeric and date values. For dates, support is provided up to the seconds interval.
* **Labels** - Render labels for date and numeric values with the option to customize their formats based on your requirements.
* **Ticks and divisors** - Provides the option to show ticks and divisors based on the slider interval. Also, minor ticks can be enabled to indicate the values between each interval. These options present the selected value in a more intuitive way for end users.
* **Thumb icon support** - Accepts custom widgets like icon or text inside the thumb.
* **Tooltip** - Render a tooltip to show the selected value clearly. You can also customize the format of the text shown in the tooltip.
* **Highly customizable** - In addition to the rich set of built-in features, the control is fully customizable through its wide range options.
* **Orientation** - Supports both horizontal and vertical orientations.

Просмотреть файл

@ -1,266 +0,0 @@
---
layout: post
title: Colors Customization in Flutter Treemap widget | Syncfusion
description: Learn here all about the Colors Customization feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Colors Customization in Flutter Treemap (SfTreemap)
This section explains about the customization of color for the tiles based on specific value or range of values.
## Level color
You can apply uniform color to the whole level using the [`TreemapLevel.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/color.html) property.
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'Germany',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(
groupMapper: (int index) => _source[index].country,
color: Colors.cyan,
padding: EdgeInsets.all(1.5),
),
TreemapLevel(
groupMapper: (int index) => _source[index].job,
color: Colors.pink[200],
padding: EdgeInsets.all(10),
),
TreemapLevel(
groupMapper: (int index) => _source[index].group,
color: Colors.green[400],
padding: EdgeInsets.all(10),
),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![Levels color customization](images/colors/levels-color.png)
N>
* Refer the [`TreemapColorMapper.value`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.value.html), for applying tile color based on specific value.
* Refer the [`TreemapColorMapper.range`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.range.html), for applying tile color based on range of values.
## Equal color mapping
If you return a value of different type other than the color from the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html), then you must set the [`colorMappers`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/colorMappers.html) property which is a collection of [`TreemapColorMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper-class.html).
The value returned from the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html) callback will be used for the comparison in the [`TreemapColorMapper.value`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.value.html). For the matched values, the [`TreemapColorMapper.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/color.html) will be applied to the respective tiles.
N> You can customize the legend icons color and texts using the [`TreemapColorMapper.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/color.html) and the [`TreemapColorMapper.value`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.value.html) properties respectively.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
late List<TreemapColorMapper> _colorMappers;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
_colorMappers = <TreemapColorMapper>[
TreemapColorMapper.value(value: 'Facebook', color: Colors.blue[200]!),
TreemapColorMapper.value(value: 'Instagram', color: Colors.deepOrange),
TreemapColorMapper.value(value: 'Twitter', color: Colors.blue[800]!),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
padding: const EdgeInsets.all(2.5),
groupMapper: (int index) {
return _source[index].country;
},
labelBuilder: (BuildContext context, TreemapTile tile) {
return Text(_source[tile.indices[0]].socialMedia);
},
colorValueMapper: (TreemapTile tile) {
return _source[tile.indices[0]].socialMedia;
},
),
],
colorMappers: _colorMappers,
),
);
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Equal color mapping](images/colors/equal-color-mapping.png)
N>
* Refer the [`TreemapColorMapper.range`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.range.html), for applying color based on range of values.
## Range color mapping
If you return a range value in the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html), then you must set the [`colorMappers`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/colorMappers.html) property.
The value returned from the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html) callback will be checked whether it lies in the [`TreemapColorMapper.from`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/from.html) and [`TreemapColorMapper.to`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/to.html) range. For the matched values, the [`TreemapColorMapper.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/color.html) will be applied to the respective tiles.
N> You can customize the legend icons color and texts using the [`TreemapColorMapper.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/color.html) and the [`TreemapColorMapper.from`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/from.html) and [`TreemapColorMapper.to`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/to.html) properties.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
late List<TreemapColorMapper> _colorMappers;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
_colorMappers = <TreemapColorMapper>[
TreemapColorMapper.range(from: 0, to: 10, color: Colors.blue[200]!),
TreemapColorMapper.range(from: 10, to: 20, color: Colors.deepOrange),
TreemapColorMapper.range(from: 20, to: 30, color: Colors.blue[800]!),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
padding: EdgeInsets.all(2.5),
groupMapper: (int index) {
return _source[index].country;
},
colorValueMapper: (TreemapTile tile) {
return tile.weight;
},
),
],
colorMappers: _colorMappers,
),
);
}
class SocialMediaUsers {
SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Range color mapping](images/colors/range-color-mapping.png)
N>
* Refer the [`TreemapColorMapper.value`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapColorMapper/TreemapColorMapper.value.html), for applying color to the tiles based on the specific value.

Просмотреть файл

@ -1,373 +0,0 @@
---
layout: post
title: Getting started with Flutter Treemap widget | Syncfusion
description: Learn here about getting started with Syncfusion Flutter Treemap (SfTreemap) widget, its elements, and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Getting started with Flutter Treemap (SfTreemap)
This section explains the steps required to add the treemap widget and enable its features such as labels, tooltip, assigning colors based on region, and legends. This section covers only basic features needed to know to get started with Syncfusion treemap.
## Add Flutter treemap to an application
Create a simple project using the instructions given in the [Getting Started with your first Flutter app](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter Treemap dependency to your pubspec.yaml file.
{% highlight dart %}
dependencies:
syncfusion_flutter_treemap: ^xx.x.xx
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of [`Syncfusion Flutter Treemap`](https://pub.dev/packages/syncfusion_flutter_treemap/versions) package.
**Get packages**
Run the following command to get the required packages.
{% highlight dart %}
$ flutter pub get
{% endhighlight %}
**Import package**
Import the following package in your Dart code.
{% tabs %}
{% highlight Dart %}
import 'package:syncfusion_flutter_treemap/treemap.dart';
{% endhighlight %}
{% endtabs %}
## Initialize treemap and populate data source
After importing the package, initialize the treemap widget as a child of any widget.
To populate the data source, set its count to the [`dataCount`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/dataCount.html) property of the treemap. The data will be grouped based on the values returned from the [`TreemapLevel.groupMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html) callback. You can have more than one TreemapLevel in the [`levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection to form a hierarchical treemap. The quantitative value of the underlying data has to be returned from the [`weightValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/weightValueMapper.html) callback. Based on this value, every tile (rectangle) will have its size.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers(
country: 'India', socialMedia: 'Facebook', usersInMillions: 25.4),
SocialMediaUsers(
country: 'USA', socialMedia: 'Instagram', usersInMillions: 19.11),
SocialMediaUsers(
country: 'Japan', socialMedia: 'Facebook', usersInMillions: 13.3),
SocialMediaUsers(
country: 'Germany', socialMedia: 'Instagram', usersInMillions: 10.65),
SocialMediaUsers(
country: 'France', socialMedia: 'Twitter', usersInMillions: 7.54),
SocialMediaUsers(
country: 'UK', socialMedia: 'Instagram', usersInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(10),
child: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
),
],
),
),
),
);
}
class SocialMediaUsers {
const SocialMediaUsers({
required this.country,
required this.socialMedia,
required this.usersInMillions,
});
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap default view](images/getting-started/default-view.png)
N>
* Refer the [`SfTreemap.levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html), for adding flat or hierarchical structured treemap.
* Refer the [`SfTreemap.colorMappers`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/colorMappers.html), for customizing the tiles color.
## Add labels
You can add any type of custom widgets to the tiles as labels based on the index using the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html) property.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers(
country: 'India', socialMedia: 'Facebook', usersInMillions: 25.4),
SocialMediaUsers(
country: 'USA', socialMedia: 'Instagram', usersInMillions: 19.11),
SocialMediaUsers(
country: 'Japan', socialMedia: 'Facebook', usersInMillions: 13.3),
SocialMediaUsers(
country: 'Germany', socialMedia: 'Instagram', usersInMillions: 10.65),
SocialMediaUsers(
country: 'France', socialMedia: 'Twitter', usersInMillions: 7.54),
SocialMediaUsers(
country: 'UK', socialMedia: 'Instagram', usersInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(10),
child: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.only(left: 2.5, right: 2.4, top: 1),
child: Text(tile.group),
);
},
),
],
),
),
),
);
}
class SocialMediaUsers {
const SocialMediaUsers({
required this.country,
required this.socialMedia,
required this.usersInMillions,
});
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap labels](images/getting-started/labels.png)
## Add tooltip
You can enable tooltip for any tile in the treemap and able to return the completely customized widget using the [`tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html) property.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers(
country: 'India', socialMedia: 'Facebook', usersInMillions: 25.4),
SocialMediaUsers(
country: 'USA', socialMedia: 'Instagram', usersInMillions: 19.11),
SocialMediaUsers(
country: 'Japan', socialMedia: 'Facebook', usersInMillions: 13.3),
SocialMediaUsers(
country: 'Germany', socialMedia: 'Instagram', usersInMillions: 10.65),
SocialMediaUsers(
country: 'France', socialMedia: 'Twitter', usersInMillions: 7.54),
SocialMediaUsers(
country: 'UK', socialMedia: 'Instagram', usersInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(10),
child: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
tooltipSettings: TreemapTooltipSettings(color: Colors.black),
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.only(left: 2.5, right: 2.4, top: 1),
child: Text(tile.group),
);
},
tooltipBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: const EdgeInsets.only(
left: 5, right: 5, top: 2, bottom: 3),
child: Text(
'Country : ${tile.group}\nSocial media : ${tile.weight}M',
style: TextStyle(color: Colors.white)),
);
},
),
],
),
),
),
);
}
class SocialMediaUsers {
const SocialMediaUsers({
required this.country,
required this.socialMedia,
required this.usersInMillions,
});
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap tooltip](images/getting-started/tooltip.png)
## Add legend
You can show legend by initializing the [`legend`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/legend.html) property in the [`SfTreemap`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap-class.html). It is possible to customize the legend item's color and text using the [`SfTreemap.colorMappers`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/colorMappers.html) property.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers(
country: 'India', socialMedia: 'Facebook', usersInMillions: 25.4),
SocialMediaUsers(
country: 'USA', socialMedia: 'Instagram', usersInMillions: 19.11),
SocialMediaUsers(
country: 'Japan', socialMedia: 'Facebook', usersInMillions: 13.3),
SocialMediaUsers(
country: 'Germany', socialMedia: 'Instagram', usersInMillions: 10.65),
SocialMediaUsers(
country: 'France', socialMedia: 'Twitter', usersInMillions: 7.54),
SocialMediaUsers(
country: 'UK', socialMedia: 'Instagram', usersInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(10),
child: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
tooltipSettings: TreemapTooltipSettings(color: Colors.black),
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.only(left: 2.5, right: 2.4, top: 1),
child: Text(tile.group),
);
},
tooltipBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: const EdgeInsets.only(
left: 5, right: 5, top: 2, bottom: 3),
child: Text(
'Country : ${tile.group}\nSocial media : ${tile.weight}M',
style: TextStyle(color: Colors.white)),
);
},
),
],
legend: TreemapLegend(),
),
),
),
);
}
class SocialMediaUsers {
const SocialMediaUsers({
required this.country,
required this.socialMedia,
required this.usersInMillions,
});
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap legend](images/getting-started/legend.png)

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 14 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 14 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 23 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 29 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 16 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 80 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 51 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 57 KiB

Двоичные данные
Flutter/treemap/images/labels/labels-support.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 57 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 21 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 86 KiB

Двоичные данные
Flutter/treemap/images/legend/bar-legend.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 20 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 80 KiB

Двоичные данные
Flutter/treemap/images/legend/default-legend.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 20 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 22 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 20 KiB

Двоичные данные
Flutter/treemap/images/legend/text-style.png

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 23 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 13 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 3.5 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 13 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 24 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 21 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 80 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 86 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 29 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 26 KiB

Просмотреть файл

@ -1,89 +0,0 @@
---
layout: post
title: Item Builder in Flutter Treemap widget | Syncfusion
description: Learn here all about the Item Builder feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Item Builder in Flutter Treemap (SfTreemap)
You can add any type of custom widgets such as image widget as a background of the tiles to easily visualize the type of data that a particular tile shows.
## Add images
You can add images as a background of the tiles using the [`TreemapLevel.itemBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/itemBuilder.html) callback.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
itemBuilder: (BuildContext context, TreemapTile tile) {
return Align(
alignment: Alignment.center,
child: Image.asset(
_getImageSource(tile)!,
),
);
},
),
],
),
);
}
String? _getImageSource(TreemapTile tile) {
if (_source[tile.indices[0]].socialMedia == 'Facebook') {
return 'images/facebook.png';
} else if (_source[tile.indices[0]].socialMedia == 'Instagram') {
return 'images/instagram.png';
} else if (_source[tile.indices[0]].socialMedia == 'Twitter') {
return 'images/twitter.png';
}
return null;
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![item builder support](images/item-builder/item-builder-support.png)
N>
* Refer the [`Align`](https://api.flutter.dev/flutter/widgets/Align-class.html) widget, to change the position of the widget.
* Refer the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html), to add labels on the tiles.

Просмотреть файл

@ -1,407 +0,0 @@
---
layout: post
title: Labels in Flutter Treemap widget | Syncfusion
description: Learn here all about adding the Labels feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Labels in Flutter Treemap (SfTreemap)
You can add any type of widgets like text widget to improve the readability of the individual tiles by providing brief descriptions on labels.
## Add labels
You can add labels on the tiles using the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html) callback which is available in the [`SfTreemap.levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection.
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(country: 'America', job: 'Management', vacancy: 40),
JobVacancyModel(country: 'America', job: 'Accounts', vacancy: 60),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Executive', vacancy: 30),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Analyst', vacancy: 40),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 100),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 30),
JobVacancyModel(country: 'UK', job: 'HR Executives', vacancy: 60),
JobVacancyModel(country: 'UK', job: 'Marketing', vacancy: 40),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(
groupMapper: (int index) => _source[index].country,
color: Colors.pink,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(tile.group),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].job,
color: Colors.green,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(tile.group),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].group,
color: Colors.blue,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(tile.group),
);
},
),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![Labels support](images/labels/labels-support.png)
## Overflow mode
You can trim or fade the label when it is overflowed from the tile using the [`Text.overflow`](https://api.flutter.dev/flutter/widgets/Text/overflow.html) property. The possible values are `visible`, `ellipsis`, `clip` and `fade`. The default value of the [`Text.overflow`](https://api.flutter.dev/flutter/widgets/Text/overflow.html)property is `TextOverflow.visible`.
By default, the labels will render even if it overflows from the tile.
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(country: 'America', job: 'Management', vacancy: 40),
JobVacancyModel(country: 'America', job: 'Accounts', vacancy: 60),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Executive', vacancy: 30),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Analyst', vacancy: 40),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 100),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 30),
JobVacancyModel(country: 'UK', job: 'HR Executives', vacancy: 60),
JobVacancyModel(country: 'UK', job: 'Marketing', vacancy: 40),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(
groupMapper: (int index) => _source[index].country,
color: Colors.pink,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(
tile.group,
overflow: TextOverflow.ellipsis,
),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].job,
color: Colors.green,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(
tile.group,
overflow: TextOverflow.ellipsis,
),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].group,
color: Colors.blue,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Text(
tile.group,
overflow: TextOverflow.ellipsis,
),
);
},
),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![Labels overflow support](images/labels/labels-overflow-mode.png)
## Alignment
You can change the labels alignment by wrapping the text widget using the [`Align`](https://api.flutter.dev/flutter/widgets/Align-class.html) widget and set the [`alignment`](https://api.flutter.dev/flutter/widgets/Align/alignment.html) property.
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(country: 'America', job: 'Management', vacancy: 40),
JobVacancyModel(country: 'America', job: 'Accounts', vacancy: 60),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Executive', vacancy: 30),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Analyst', vacancy: 40),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 100),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 30),
JobVacancyModel(country: 'UK', job: 'HR Executives', vacancy: 60),
JobVacancyModel(country: 'UK', job: 'Marketing', vacancy: 40),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(
groupMapper: (int index) => _source[index].country,
color: Colors.pink,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Align(
alignment: Alignment.center,
child: Text(tile.group),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].job,
color: Colors.green,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Align(
alignment: Alignment.center,
child: Text(tile.group),
);
},
),
TreemapLevel(
groupMapper: (int index) => _source[index].group,
color: Colors.blue,
labelBuilder: (BuildContext context, TreemapTile tile) {
return Align(
alignment: Alignment.center,
child: Text(tile.group),
);
},
),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![labels alignment](images/labels/labels-alignment.png)

Просмотреть файл

@ -1,190 +0,0 @@
---
layout: post
title: Layouts in Flutter Treemap widget | Syncfusion
description: Learn here all about adding different layouts of the Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Layouts in Flutter Treemap (SfTreemap)
This section explains the different layouts in the treemap widget. The available layouts are,
* Squarified
* Slice
* Dice
## Squarified
The [`squarified`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/SfTreemap.html) layout will arrange the rectangles in a row and wrap them to the next row according to the available size. The size of the particular rectangle is based on the value returned from [`weightValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/weightValueMapper.html) callback. By default, squarified layout is used.
{% tabs %}
{% highlight Dart %}
late List<PopulationModel> _dataSource;
@override
void initState() {
_dataSource = <PopulationModel>[
PopulationModel(continent: 'Asia', populationInMillions: 25.4),
PopulationModel(continent: 'South America', populationInMillions: 19.11),
PopulationModel(continent: 'North America', populationInMillions: 13.3),
PopulationModel(continent: 'Europe', populationInMillions: 10.65),
PopulationModel(continent: 'Africa', populationInMillions: 7.54),
PopulationModel(continent: 'Australia', populationInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _dataSource.length,
weightValueMapper: (int index) {
return _dataSource[index].populationInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _dataSource[index].continent;
},
color: Colors.teal[200],
padding: const EdgeInsets.all(1.5),
),
],
),
);
}
class PopulationModel {
const PopulationModel({
required this.continent,
required this.populationInMillions,
});
final String continent;
final double populationInMillions;
}
{% endhighlight %}
{% endtabs %}
![Squarified layout structure](images/layout/squarified-layout.png)
## Slice
The [`slice`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/SfTreemap.slice.html) layout will start to arrange each rectangle in a horizontal direction and the size of the rectangle will be based on the value returned from [`weightValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/weightValueMapper.html) callback and the available height.
{% tabs %}
{% highlight Dart %}
late List<PopulationModel> _dataSource;
@override
void initState() {
_dataSource = <PopulationModel>[
PopulationModel(continent: 'Asia', populationInMillions: 25.4),
PopulationModel(continent: 'South America', populationInMillions: 19.11),
PopulationModel(continent: 'North America', populationInMillions: 13.3),
PopulationModel(continent: 'Europe', populationInMillions: 10.65),
PopulationModel(continent: 'Africa', populationInMillions: 7.54),
PopulationModel(continent: 'Australia', populationInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap.slice(
dataCount: _dataSource.length,
weightValueMapper: (int index) {
return _dataSource[index].populationInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _dataSource[index].continent;
},
color: Colors.teal[200],
padding: const EdgeInsets.all(1.5),
),
],
),
);
}
class PopulationModel {
const PopulationModel({
required this.continent,
required this.populationInMillions,
});
final String continent;
final double populationInMillions;
}
{% endhighlight %}
{% endtabs %}
![Slice layout structure](images/layout/slice-layout.png)
## Dice
The [`dice`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/SfTreemap.dice.html) structure will start to arrange each rectangle in the vertical direction and the size of the rectangle will be based on the value returned from the [`weightValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/weightValueMapper.html) callback and the available width.
{% tabs %}
{% highlight Dart %}
late List<PopulationModel> _dataSource;
@override
void initState() {
_dataSource = <PopulationModel>[
PopulationModel(continent: 'Asia', populationInMillions: 25.4),
PopulationModel(continent: 'South America', populationInMillions: 19.11),
PopulationModel(continent: 'North America', populationInMillions: 13.3),
PopulationModel(continent: 'Europe', populationInMillions: 10.65),
PopulationModel(continent: 'Africa', populationInMillions: 7.54),
PopulationModel(continent: 'Australia', populationInMillions: 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap.dice(
dataCount: _dataSource.length,
weightValueMapper: (int index) {
return _dataSource[index].populationInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _dataSource[index].continent;
},
color: Colors.teal[200],
padding: const EdgeInsets.all(1.5),
),
],
),
);
}
class PopulationModel {
const PopulationModel({
required this.continent,
required this.populationInMillions,
});
final String continent;
final double populationInMillions;
}
{% endhighlight %}
{% endtabs %}
![Dice layout structure](images/layout/dice-layout.png)

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,344 +0,0 @@
---
layout: post
title: Flat and Hierarchical Levels in Flutter Treemap | Syncfusion
description: Learn here all about the Flat and Hierarchical Levels feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Flat and Hierarchical Levels in Flutter Treemap (SfTreemap)
The levels of the treemap can be categorized into the following two types,
* Flat level.
* Hierarchical level.
## Flat level
There will be a tile for each unique value returned in the [`TreemapLevel.groupMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html) callback which is added to the [`levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection property of [`SfTreemap`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap-class.html).
### Squarified
{% tabs %}
{% highlight Dart %}
late List<PopulationModel> _source;
@override
void initState() {
_source = <PopulationModel>[
PopulationModel('Asia', 25.4),
PopulationModel('South America', 19.11),
PopulationModel('North America', 13.3),
PopulationModel('Europe', 10.65),
PopulationModel('Africa', 7.54),
PopulationModel('Australia', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].populationInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].continent;
},
),
],
),
);
}
class PopulationModel {
const PopulationModel(this.continent, this.populationInMillions);
final String continent;
final double populationInMillions;
}
{% endhighlight %}
{% endtabs %}
![Squarified flat level](images/levels/squarified-flat-level.png)
N>
* Refer the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html), for customizing the tile color.
* Refer the [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html), for adding and customizing the tooltip on the treemap.
* Refer the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html), for adding and customizing the label on the tile.
* Refer the [`TreemapLevel.itemBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/itemBuilder.html), for adding and customizing the custom widget on the treemap.
## Hierarchical level
Hierarchical level arrange the tiles in the form of nested rectangles. Each tile of the treemap is a rectangle which is filled with smaller rectangles representing sub-data. You can have more than one [`TreemapLevel`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel-class.html) in the [`levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection to form a hierarchical treemap.
The first level will work similarly to the flat level. From the next level in the [`levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection, the items returned from the [`TreemapLevel.groupMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html) for the indices, will be placed inside the rectangle for the same indices returned from the [`TreemapLevel.groupMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/groupMapper.html) in the previous level. This will go on until the last level in the [`levels`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/levels.html) collection.
### Squarified
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(country: 'America', job: 'Management', vacancy: 40),
JobVacancyModel(country: 'America', job: 'Accounts', vacancy: 60),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Executive', vacancy: 30),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Analyst', vacancy: 40),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 100),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 30),
JobVacancyModel(country: 'UK', job: 'HR Executives', vacancy: 60),
JobVacancyModel(country: 'UK', job: 'Marketing', vacancy: 40),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(groupMapper: (int index) => _source[index].country),
TreemapLevel(groupMapper: (int index) => _source[index].job),
TreemapLevel(groupMapper: (int index) => _source[index].group),
TreemapLevel(groupMapper: (int index) => _source[index].role),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![Squarified hierarchical level](images/levels/squarified-hierarchical-level.png)
N>
* Refer the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html), for customizing the tile color.
* Refer the [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html), for adding and customizing the tooltip on the treemap.
* Refer the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html), for adding and customizing the label on the tile.
* Refer the [`TreemapLevel.itemBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/itemBuilder.html), for adding and customizing the custom widget on the treemap.
## Appearance customization
You can customize the levels using the following properties:
* **Padding** - Specifies the gap between the groups. The default value of the [`TreemapLevel.padding`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/padding.html) property is `EdgeInsets.all(1.0)`.
* **Color** - Specifies the background color for the group using the [`TreemapLevel.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/color.html) property.
* **Border** - Specifies the border color, border width and border radius for the group using the [`TreemapLevel.border`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/border.html) property.
### Squarified
{% tabs %}
{% highlight Dart %}
late List<JobVacancyModel> _source;
@override
void initState() {
_source = <JobVacancyModel>[
JobVacancyModel(country: 'America', job: 'Sales', vacancy: 70),
JobVacancyModel(
country: 'America', job: 'Technical', group: 'Testers', vacancy: 35),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 105),
JobVacancyModel(
country: 'America',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 40),
JobVacancyModel(country: 'America', job: 'Management', vacancy: 40),
JobVacancyModel(country: 'America', job: 'Accounts', vacancy: 60),
JobVacancyModel(
country: 'India', job: 'Technical', group: 'Testers', vacancy: 25),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 155),
JobVacancyModel(
country: 'India',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 60),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Executive', vacancy: 30),
JobVacancyModel(
country: 'Germany', job: 'Sales', group: 'Analyst', vacancy: 40),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Windows',
vacancy: 100),
JobVacancyModel(
country: 'UK',
job: 'Technical',
group: 'Developers',
role: 'Web',
vacancy: 30),
JobVacancyModel(country: 'UK', job: 'HR Executives', vacancy: 60),
JobVacancyModel(country: 'UK', job: 'Marketing', vacancy: 40),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].vacancy;
},
levels: [
TreemapLevel(
groupMapper: (int index) => _source[index].country,
color: Colors.blue,
border: RoundedRectangleBorder(
side: BorderSide(
color: Colors.blue,
width: 1,
),
),
padding: EdgeInsets.all(2.5),
),
TreemapLevel(
groupMapper: (int index) => _source[index].job,
color: Colors.orangeAccent,
border: RoundedRectangleBorder(
side: BorderSide(
color: Colors.orangeAccent,
width: 1,
),
),
padding: EdgeInsets.all(2.5),
),
TreemapLevel(
groupMapper: (int index) => _source[index].group,
color: Colors.green[300],
border: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green,
width: 1,
),
),
padding: EdgeInsets.all(5),
),
TreemapLevel(
groupMapper: (int index) => _source[index].role,
color: Colors.pink[300],
border: RoundedRectangleBorder(
side: BorderSide(
color: Colors.pink,
width: 1,
),
),
padding: EdgeInsets.all(5),
),
],
),
);
}
class JobVacancyModel {
const JobVacancyModel(
{required this.country,
required this.job,
this.group,
this.role,
required this.vacancy});
final String country;
final String job;
final String? group;
final String? role;
final double vacancy;
}
{% endhighlight %}
{% endtabs %}
![Appearance customized levels](images/levels/levels-customization.png)
N>
* Refer the [`TreemapLevel.colorValueMapper`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/colorValueMapper.html), for customizing the tile color.
* Refer the [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html), for adding and customizing the tooltip on the treemap.
* Refer the [`TreemapLevel.labelBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/labelBuilder.html), for adding and customizing the label on the tile.
* Refer the [`TreemapLevel.itemBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/itemBuilder.html), for adding and customizing the custom widget on the treemap.

Просмотреть файл

@ -1,140 +0,0 @@
---
layout: post
title: Tile selection in Flutter Treemap widget | Syncfusion
description: Learn here all about the Tile selection feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Tile selection in Flutter Treemap (SfTreemap)
You can select a tile in order to highlight that area on a treemap. You can use the callback for performing any action during tile selection.
## Enable tile selection
You can enable tile selection on a treemap using the [`SfTreemap.onSelectionChanged`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/onSelectionChanged.html) property. The descendant tiles of the selected tile are also selected along with the selected tile when doing selection for hierarchical level.
The [`onSelectionChanged`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/SfTreemap/onSelectionChanged.html) callback will be called with the details of the selected tile when the user is selecting a tile by tapping and you will be able to do any specific functionalities like showing pop-up or navigate to a different page.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
onSelectionChanged: (TreemapTile) {},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
),
],
),
);
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Enable tile selection](images/selection/enable-tile-selection.gif)
N>
* Refer the [`TreemapSelectionSettings`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapSelectionSettings-class.html), for customizing the selected tile's appearance.
## Appearance customization
You can customize the below appearance of the selected tile.
* **Background color** - Change the background color of the selected tile using the [`TreemapSelectionSettings.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapSelectionSettings/color.html) property.
* **Border** - Change the border color, border stroke width using the [`BorderSide.color`](https://api.flutter.dev/flutter/painting/BorderSide/color.html) and [`BorderSide.width`](https://api.flutter.dev/flutter/painting/BorderSide/width.html) properties in the [`RoundedRectangleBorder`](https://api.flutter.dev/flutter/painting/RoundedRectangleBorder-class.html). Also apply rounded border using the [`RoundedRectangleBorder.borderRadius`](https://api.flutter.dev/flutter/painting/RoundedRectangleBorder/borderRadius.html) property.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
onSelectionChanged: (TreemapTile) {},
selectionSettings: TreemapSelectionSettings(
color: Colors.orange,
border: RoundedRectangleBorder(
side: BorderSide(
color: Colors.deepOrange,
width: 1,
),
borderRadius: BorderRadius.circular(10),
),
),
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
),
],
),
);
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Selection customization](images/selection/selection-customization.gif)

Просмотреть файл

@ -1,202 +0,0 @@
---
layout: post
title: Tooltip in Flutter Treemap widget | Syncfusion
description: Learn here all about adding the Tooltip feature of Syncfusion Flutter Treemap (SfTreemap) widget and more.
platform: Flutter
control: SfTreemap
documentation: ug
---
# Tooltip in Flutter Treemap (SfTreemap)
Tooltip is used to provide information about the tile during the tap, or click interaction. This section helps to learn about how to show tooltip on a tile and customize them.
## Tooltip for the tiles
It is used to clearly indicate the tile information on the tap or click. To show tooltip for the tile, return a widget in [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html). This widget will then be wrapped in the builtin shape which comes with the nose at the bottom.
The [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html) will be called with the corresponding tile details every time you interact with the tile i.e., while tapping in touch devices and hover enter in the mouse enabled devices.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
tooltipBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Country : ',
style: TextStyle(color: Colors.white)),
Text(tile.group, style: TextStyle(color: Colors.white)),
],
),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Social media : ',
style: TextStyle(color: Colors.white)),
Text(tile.weight.toString(),
style: TextStyle(color: Colors.white)),
],
),
],
),
);
},
),
],
),
);
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap tooltip builder](images/tooltip/tile_tooltip_builder.png)
N>
* Refer the [`TreemapTooltipSettings`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapTooltipSettings/TreemapTooltipSettings.html), for customizing the tooltip shape.
## Appearance customization
You can customize the appearance of the tooltip.
* **Background color** - Change the background color of the tooltip in the treemap using the [`TreemapTooltipSettings.color`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapTooltipSettings/color.html) property.
* **Border color** - Change the border color of the tooltip in the treemap using the [`TreemapTooltipSettings.borderColor`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapTooltipSettings/borderColor.html) property.
* **Border width** - Change the border width of the tooltip in the treemap using the [`TreemapTooltipSettings.borderWidth`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapTooltipSettings/borderWidth.html) property.
* **Border radius** - Change the border radius of the tooltip in the treemap using the [`TreemapTooltipSettings.borderRadius`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapTooltipSettings/borderRadius.html) property.
{% tabs %}
{% highlight Dart %}
late List<SocialMediaUsers> _source;
@override
void initState() {
_source = <SocialMediaUsers>[
SocialMediaUsers('India', 'Facebook', 25.4),
SocialMediaUsers('USA', 'Instagram', 19.11),
SocialMediaUsers('Japan', 'Facebook', 13.3),
SocialMediaUsers('Germany', 'Instagram', 10.65),
SocialMediaUsers('France', 'Twitter', 7.54),
SocialMediaUsers('UK', 'Instagram', 4.93),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfTreemap(
dataCount: _source.length,
weightValueMapper: (int index) {
return _source[index].usersInMillions;
},
levels: [
TreemapLevel(
groupMapper: (int index) {
return _source[index].country;
},
tooltipBuilder: (BuildContext context, TreemapTile tile) {
return Padding(
padding: EdgeInsets.all(5),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Country : '),
Text(tile.group),
],
),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Social media : '),
Text(tile.weight.toString()),
],
),
],
),
);
},
),
],
tooltipSettings: TreemapTooltipSettings(
color: Colors.orange[300],
borderColor: Colors.deepOrange[900],
borderWidth: 2,
borderRadius: BorderRadius.circular(10),
),
),
);
}
class SocialMediaUsers {
const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);
final String country;
final String socialMedia;
final double usersInMillions;
}
{% endhighlight %}
{% endtabs %}
![Treemap tooltip appearance customization](images/tooltip/tooltip_customization.png)
N>
* Refer the [`TreemapLevel.tooltipBuilder`](https://pub.dev/documentation/syncfusion_flutter_treemap/latest/treemap/TreemapLevel/tooltipBuilder.html), for enabling tooltip for the tile.

Просмотреть файл

@ -1,194 +0,0 @@
---
layout: post
title: Getting Started for Syncfusion Flutter XlsIO
description: Learn how to create Excel document with all basic elements and save it in browser or mobile devices by using Syncfusion Flutter XlsIO.
platform: flutter
control: Excel
documentation: ug
---
# Getting Started for Syncfusion Flutter XlsIO
This section explains the steps required to create a Excel document by few lines of code. This section covers only the minimal features needed to learn to get started with the Excel.
## Steps to create Excel document in Flutter application
Create a simple project using the instructions given in the [`Getting Started with your first Flutter app'](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app) documentation.
**Add dependency**
Add the Syncfusion Flutter XlsIO dependency to your pub spec file.
{% highlight dart %}
dependencies:
syncfusion_flutter_xlsio: ^xx.x.xx
{% endhighlight %}
N> Here **xx.x.xx** denotes the current version of ['Syncfusion Flutter XlsIO'](https://pub.dev/packages/syncfusion_flutter_xlsio/versions) package.
**Get packages**
Run the following command to get the required packages.
{% highlight dart %}
$ flutter pub get
{% endhighlight %}
**Import package**
Import the following package in your Dart code.
{% highlight dart %}
import 'package:syncfusion_flutter_xlsio/xlsio.dart';
{% endhighlight %}
Add a new button widget as a child of your container widget.
{% highlight dart %}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: _createExcel,
child: Text('Create Excel')
)
)
);
}
{% endhighlight %}
Include the following code snippet in the button click event to create a Excel file.
{% highlight dart %}
Future<void> _createExcel() async {
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing worksheet via index.
final Worksheet sheet = workbook.worksheets[0];
// Set the text value.
sheet.getRangeByName('A1').setText('Hello World!');
// Save and dispose the document.
final List<int> bytes = workbook.saveAsStream();
workbook.dispose();
// Save the Excel file in the local machine.
File('Output.xlsx').writeAsBytes(bytes);
}
{% endhighlight %}
## Create a Excel document in mobile
You can create a Excel document in mobile by using the following steps:
**Add dependency**
Add the following packages to your pub spec file.
{% highlight dart %}
path_provider: ^1.6.5
open_file: ^3.0.1
{% endhighlight %}
**Import package**
{% highlight dart %}
import 'dart:io';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
{% endhighlight %}
Include the following code snippet to create a Excel document in mobile.
{% highlight dart %}
Future<void> _createExcel() async {
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing worksheet via index.
final Worksheet sheet = workbook.worksheets[0];
// Set the text value.
sheet.getRangeByName('A1').setText('Hello World!');
// Save and dispose the document.
final List<int> bytes = workbook.saveAsStream();
workbook.dispose();
// Get external storage directory
final directory = await getExternalStorageDirectory();
// Get directory path
final path = directory.path;
// Create an empty file to write Excel data
File file = File('$path/Output.xlsx');
// Write Excel data
await file.writeAsBytes(bytes, flush: true);
// Open the Excel document in mobile
OpenFile.open('$path/Output.xlsx');
}
{% endhighlight %}
## Create a Excel document in web
You can create a Excel document in web by using the following steps.
**Import package**
{% highlight dart %}
import 'dart:convert';
import 'dart:html';
{% endhighlight %}
Include the following code snippet to create a excel document in web.
{% highlight dart %}
Future<void> _createExcel() async {
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing worksheet via index.
final Worksheet sheet = workbook.worksheets[0];
// Set the text value.
sheet.getRangeByName('A1').setText('Hello World!');
// Save and dispose the document.
final List<int> bytes = workbook.saveAsStream();
workbook.dispose();
//Download the output file in web.
AnchorElement(
href:
"data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}")
..setAttribute("download", "output.xlsx")
..click();
{% endhighlight %}

Просмотреть файл

@ -1,101 +0,0 @@
---
layout: post
title: Excel Data Syncfusion Flutter XlsIO
description: In this section,Learn how to import data to Excel document from objects, Collections, List using Syncfusion Flutter XlsIO.
platform: flutter
control: Excel
documentation: ug
---
# Importing Data to Worksheets
Flutter XlsIO provides the ability to import data into a worksheet using List\<Object>.
## Import Data from List\<Object>
Using **importList** method, we can import list of data with different data types.
The following code snippet shows how to import a list of data vertically into the worksheet using **importList()** method.
{% highlight dart %}
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing sheet via index.
final Worksheet sheet = workbook.worksheets[0];
//Initialize the List\<Object>
final List<Object> list = [
'Toatal Income',
20000,
'On Date',
DateTime(2021, 11, 11)
];
// Represent the starting row.
final int firstRow = 1;
// Represent the starting column.
final int firstColumn = 1;
// Represents that the data should be imported vertically.
final bool isVertical = true;
//Import the Object list to Sheet
sheet.importList(list, firstRow, firstColumn, isVertical);
sheet.autoFitColumn(1);
// Save and dispose workbook.
final List<int>? bytes = workbook.saveAsStream();
File('Importlist.xlsx').writeAsBytes(bytes!);
workbook.dispose();
{% endhighlight %}
The following screenshot represents the Excel file generated by vertically importing data from a List\<Object> into the Excel worksheet using the Flutter XlsIO.
![importList](images/ImportListV.jpg)
The following code snippet shows how to import a list of data horizontally into the worksheet using **importList()** method.
{% highlight dart %}
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing sheet via index.
final Worksheet sheet = workbook.worksheets[0];
//Initialize the List\<Object>
final List<Object> list = [
'Toatal Income',
20000,
'On Date',
DateTime(2021, 11, 11)
];
// Represent the starting row.
final int firstRow = 1;
// Represent the starting column.
final int firstColumn = 1;
// Represents that the data should be imported horizontally.
final bool isVertical = false;
//Import the Object list to Sheet
sheet.importList(list, firstRow, firstColumn, isVertical);
sheet.getRangeByIndex(1, 1, 1, 4).autoFitColumns();
// Save and dispose workbook.
final List<int>? bytes = workbook.saveAsStream();
File('Importlist.xlsx').writeAsBytes(bytes!);
workbook.dispose();
{% endhighlight %}
The following screenshot represents the Excel file generated by horizontally importing data from a List\<Object> into the Excel worksheet using the Flutter XlsIO.
![importList](images/ImportListH.jpg)

Двоичные данные
flutter-toc.html

Двоичный файл не отображается.