feat: add Control Room with containers and stacks management
- Add Control Room page with stacks sidebar and containers list - Implement container actions (start/stop/restart) with snackbars - Add container logs viewer dialog - Add search/filter for both stacks and containers lists - Add external links for Portainer and Netdata (url_launcher) - Add VS Code launch configuration for Flutter web debugging 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.5
parent
dd6bcbdbda
commit
3b89ed8c18
@@ -0,0 +1,130 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../data_grid_source.dart';
|
||||
|
||||
/// Data source adapter for Core API endpoints.
|
||||
///
|
||||
/// Implements the DataGrid data source interface for fetching data
|
||||
/// from the Core API with support for search, sorting, and pagination.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final containersSource = CoreApiDataSource<Container>(
|
||||
/// dio: dio,
|
||||
/// endpoint: '/infrastructure/containers',
|
||||
/// fromJson: Container.fromJson,
|
||||
/// searchParam: 'search',
|
||||
/// sortParam: 'sort_by',
|
||||
/// orderParam: 'order',
|
||||
/// );
|
||||
/// ```
|
||||
class CoreApiDataSource<T> extends DataGridSource<T> {
|
||||
CoreApiDataSource({
|
||||
required this.dio,
|
||||
required this.endpoint,
|
||||
required this.fromJson,
|
||||
this.searchParam = 'search',
|
||||
this.sortParam = 'sort',
|
||||
this.orderParam = 'order',
|
||||
this.offsetParam = 'offset',
|
||||
this.limitParam = 'limit',
|
||||
this.itemsKey = 'items',
|
||||
this.totalCountKey = 'total',
|
||||
});
|
||||
|
||||
/// Dio HTTP client instance.
|
||||
final Dio dio;
|
||||
|
||||
/// API endpoint path.
|
||||
final String endpoint;
|
||||
|
||||
/// Function to parse JSON into the item type.
|
||||
final T Function(Map<String, dynamic> json) fromJson;
|
||||
|
||||
/// Query parameter name for search.
|
||||
final String searchParam;
|
||||
|
||||
/// Query parameter name for sort field.
|
||||
final String sortParam;
|
||||
|
||||
/// Query parameter name for sort order.
|
||||
final String orderParam;
|
||||
|
||||
/// Query parameter name for pagination offset.
|
||||
final String offsetParam;
|
||||
|
||||
/// Query parameter name for pagination limit.
|
||||
final String limitParam;
|
||||
|
||||
/// JSON key for items array in response.
|
||||
final String itemsKey;
|
||||
|
||||
/// JSON key for total count in response.
|
||||
final String totalCountKey;
|
||||
|
||||
@override
|
||||
Future<DataGridResult<T>> fetch({
|
||||
String? searchQuery,
|
||||
String? sortField,
|
||||
bool sortDescending = false,
|
||||
int? offset,
|
||||
int? limit,
|
||||
}) async {
|
||||
final queryParams = <String, dynamic>{};
|
||||
|
||||
if (searchQuery != null && searchQuery.isNotEmpty) {
|
||||
queryParams[searchParam] = searchQuery;
|
||||
}
|
||||
|
||||
if (sortField != null) {
|
||||
queryParams[sortParam] = sortField;
|
||||
queryParams[orderParam] = sortDescending ? 'desc' : 'asc';
|
||||
}
|
||||
|
||||
if (offset != null) {
|
||||
queryParams[offsetParam] = offset;
|
||||
}
|
||||
|
||||
if (limit != null) {
|
||||
queryParams[limitParam] = limit;
|
||||
}
|
||||
|
||||
final response = await dio.get<Map<String, dynamic>>(
|
||||
endpoint,
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
final data = response.data!;
|
||||
|
||||
// Handle both paginated and wrapped responses
|
||||
List<dynamic> itemsJson;
|
||||
int totalCount;
|
||||
|
||||
if (data.containsKey(itemsKey)) {
|
||||
// Paginated response: { items: [...], total: N }
|
||||
itemsJson = data[itemsKey] as List<dynamic>;
|
||||
totalCount = data[totalCountKey] as int? ?? itemsJson.length;
|
||||
} else {
|
||||
// Try common wrapper patterns: { data: [...] } or { results: [...] }
|
||||
itemsJson = (data['data'] ?? data['results'] ?? []) as List<dynamic>;
|
||||
totalCount = data['count'] as int? ??
|
||||
data['total'] as int? ??
|
||||
data['totalCount'] as int? ??
|
||||
itemsJson.length;
|
||||
}
|
||||
|
||||
final items = itemsJson
|
||||
.map((json) => fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final hasMore = offset != null && limit != null
|
||||
? (offset + items.length) < totalCount
|
||||
: false;
|
||||
|
||||
return DataGridResult(
|
||||
items: items,
|
||||
totalCount: totalCount,
|
||||
hasMore: hasMore,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'data_grid_config.dart';
|
||||
import 'data_grid_provider.dart';
|
||||
import 'data_grid_source.dart';
|
||||
import 'data_grid_state.dart';
|
||||
import 'widgets/data_grid_bulk_actions.dart';
|
||||
import 'widgets/data_grid_empty_state.dart';
|
||||
import 'widgets/data_grid_footer.dart';
|
||||
import 'widgets/data_grid_header.dart';
|
||||
import 'widgets/data_grid_row.dart';
|
||||
import 'widgets/data_grid_search_bar.dart';
|
||||
|
||||
/// A configurable data grid widget for displaying tabular data.
|
||||
///
|
||||
/// Features:
|
||||
/// - Sortable columns
|
||||
/// - Row selection (single and bulk)
|
||||
/// - Per-row and bulk actions
|
||||
/// - Search/filtering
|
||||
/// - Pagination or infinite scroll
|
||||
/// - Custom cell rendering
|
||||
/// - Empty, loading, and error states
|
||||
///
|
||||
/// Usage:
|
||||
/// ```dart
|
||||
/// DataGrid<Container>(
|
||||
/// provider: containersGridProvider,
|
||||
/// config: containersGridConfig,
|
||||
/// idSelector: (c) => c.id,
|
||||
/// )
|
||||
/// ```
|
||||
class DataGrid<T> extends ConsumerWidget {
|
||||
const DataGrid({
|
||||
super.key,
|
||||
required this.provider,
|
||||
required this.config,
|
||||
required this.idSelector,
|
||||
this.toolbarActions,
|
||||
});
|
||||
|
||||
/// The Riverpod provider for this grid's state.
|
||||
final StateNotifierProvider<DataGridController<T>, DataGridState<T>> provider;
|
||||
|
||||
/// Grid configuration.
|
||||
final DataGridConfig<T> config;
|
||||
|
||||
/// Function to extract unique ID from an item.
|
||||
final Object Function(T item) idSelector;
|
||||
|
||||
/// Additional actions to show in the toolbar (next to search).
|
||||
final List<Widget>? toolbarActions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final state = ref.watch(provider);
|
||||
final controller = ref.read(provider.notifier);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Toolbar: search + bulk actions + custom actions
|
||||
if (config.enableSearch ||
|
||||
(state.selectedCount > 0 && config.bulkActions.isNotEmpty) ||
|
||||
toolbarActions != null)
|
||||
_buildToolbar(context, state, controller),
|
||||
|
||||
// Header
|
||||
if (config.showHeader)
|
||||
DataGridHeader<T>(
|
||||
config: config,
|
||||
sortColumnIndex: state.sortColumnIndex,
|
||||
sortDescending: state.sortDescending,
|
||||
onSort: controller.sortBy,
|
||||
showCheckbox: config.rowsSelectable,
|
||||
allSelected: state.allSelected,
|
||||
someSelected: state.someSelected,
|
||||
onSelectAll: controller.toggleSelectAll,
|
||||
),
|
||||
|
||||
// Content area
|
||||
Expanded(
|
||||
child: _buildContent(context, state, controller),
|
||||
),
|
||||
|
||||
// Footer
|
||||
if (config.showFooter)
|
||||
DataGridFooter(
|
||||
totalCount: state.totalCount,
|
||||
displayedCount: state.items.length,
|
||||
dataMode: config.dataMode,
|
||||
currentPage: state.currentPage,
|
||||
onPageChange: controller.goToPage,
|
||||
isLoading: state.isLoading,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildToolbar(
|
||||
BuildContext context,
|
||||
DataGridState<T> state,
|
||||
DataGridController<T> controller,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
if (config.enableSearch)
|
||||
DataGridSearchBar(
|
||||
onSearch: controller.search,
|
||||
onClear: controller.clearSearch,
|
||||
hintText: config.searchHint,
|
||||
initialValue: state.searchQuery,
|
||||
),
|
||||
if (state.selectedCount > 0 && config.bulkActions.isNotEmpty) ...[
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: DataGridBulkActions<T>(
|
||||
selectedCount: state.selectedCount,
|
||||
bulkActions: config.bulkActions,
|
||||
onClearSelection: controller.clearSelection,
|
||||
getSelectedItems: controller.getSelectedItems,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
const Spacer(),
|
||||
],
|
||||
if (toolbarActions != null) ...toolbarActions!,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(
|
||||
BuildContext context,
|
||||
DataGridState<T> state,
|
||||
DataGridController<T> controller,
|
||||
) {
|
||||
// Initial loading state
|
||||
if (state.isInitialLoad && state.isLoading) {
|
||||
return config.loadingBuilder?.call(context) ??
|
||||
const DataGridLoadingState();
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (state.hasError && state.items.isEmpty) {
|
||||
return config.errorBuilder?.call(context, state.error!, controller.refresh) ??
|
||||
DataGridErrorState(
|
||||
error: state.error!,
|
||||
onRetry: controller.refresh,
|
||||
);
|
||||
}
|
||||
|
||||
// Empty state
|
||||
if (state.isEmpty) {
|
||||
return config.emptyStateBuilder?.call(context) ??
|
||||
DataGridEmptyState(
|
||||
title: state.searchQuery.isNotEmpty
|
||||
? 'No results found'
|
||||
: 'No items found',
|
||||
subtitle: state.searchQuery.isNotEmpty
|
||||
? 'Try a different search term'
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
// Data rows
|
||||
return _buildListView(state, controller);
|
||||
}
|
||||
|
||||
Widget _buildListView(
|
||||
DataGridState<T> state,
|
||||
DataGridController<T> controller,
|
||||
) {
|
||||
final isInfiniteScroll = config.dataMode is InfiniteDataMode;
|
||||
|
||||
return NotificationListener<ScrollNotification>(
|
||||
onNotification: (notification) {
|
||||
if (isInfiniteScroll &&
|
||||
notification is ScrollEndNotification &&
|
||||
notification.metrics.extentAfter < 200) {
|
||||
controller.loadMore();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
child: ListView.builder(
|
||||
itemCount: state.items.length + (state.isLoading && !state.isInitialLoad ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
// Loading indicator at bottom for infinite scroll
|
||||
if (index >= state.items.length) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
final item = state.items[index];
|
||||
final isSelected = controller.isSelected(item);
|
||||
|
||||
return DataGridRow<T>(
|
||||
item: item,
|
||||
index: index,
|
||||
config: config,
|
||||
isSelected: isSelected,
|
||||
onSelect: () => controller.toggleSelection(item),
|
||||
onTap: config.onRowTap != null ? () => config.onRowTap!(item) : null,
|
||||
backgroundColor: config.rowColor?.call(context, item, index),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Per-row action for DataGrid.
|
||||
class DataGridAction<T> {
|
||||
const DataGridAction({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onTap,
|
||||
this.showWhen,
|
||||
this.destructive = false,
|
||||
this.requiresConfirmation = false,
|
||||
this.confirmationMessage,
|
||||
});
|
||||
|
||||
/// Icon to display in the action menu.
|
||||
final IconData icon;
|
||||
|
||||
/// Label for the action.
|
||||
final String label;
|
||||
|
||||
/// Callback when the action is triggered.
|
||||
final Future<void> Function(T item) onTap;
|
||||
|
||||
/// Condition to show/hide this action for specific items.
|
||||
final bool Function(T item)? showWhen;
|
||||
|
||||
/// Whether this is a destructive action (styled differently).
|
||||
final bool destructive;
|
||||
|
||||
/// Whether to show a confirmation dialog before executing.
|
||||
final bool requiresConfirmation;
|
||||
|
||||
/// Custom confirmation message. Defaults to "Are you sure?".
|
||||
final String? confirmationMessage;
|
||||
|
||||
/// Checks if this action should be shown for the given item.
|
||||
bool shouldShow(T item) => showWhen?.call(item) ?? true;
|
||||
}
|
||||
|
||||
/// Bulk action for selected rows in DataGrid.
|
||||
class DataGridBulkAction<T> {
|
||||
const DataGridBulkAction({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onTap,
|
||||
this.minSelected = 1,
|
||||
this.maxSelected,
|
||||
this.destructive = false,
|
||||
this.requiresConfirmation = false,
|
||||
this.confirmationMessage,
|
||||
});
|
||||
|
||||
/// Icon to display.
|
||||
final IconData icon;
|
||||
|
||||
/// Label for the action.
|
||||
final String label;
|
||||
|
||||
/// Callback when the action is triggered with selected items.
|
||||
final Future<void> Function(List<T> items) onTap;
|
||||
|
||||
/// Minimum number of items that must be selected.
|
||||
final int minSelected;
|
||||
|
||||
/// Maximum number of items that can be selected (null = no limit).
|
||||
final int? maxSelected;
|
||||
|
||||
/// Whether this is a destructive action.
|
||||
final bool destructive;
|
||||
|
||||
/// Whether to show a confirmation dialog before executing.
|
||||
final bool requiresConfirmation;
|
||||
|
||||
/// Custom confirmation message.
|
||||
final String? confirmationMessage;
|
||||
|
||||
/// Checks if this action is available for the given selection count.
|
||||
bool isAvailable(int selectedCount) {
|
||||
if (selectedCount < minSelected) return false;
|
||||
if (maxSelected != null && selectedCount > maxSelected!) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Column width specification for DataGrid columns.
|
||||
sealed class DataGridColumnWidth {
|
||||
const DataGridColumnWidth._();
|
||||
|
||||
/// Fixed width in logical pixels.
|
||||
const factory DataGridColumnWidth.fixed(double width) = GridFixedWidth;
|
||||
|
||||
/// Flexible width with flex factor (like Expanded).
|
||||
const factory DataGridColumnWidth.flex([int flex]) = GridFlexWidth;
|
||||
|
||||
/// Fraction of available width (0.0 to 1.0).
|
||||
const factory DataGridColumnWidth.fraction(double fraction) =
|
||||
GridFractionWidth;
|
||||
}
|
||||
|
||||
/// Fixed column width.
|
||||
final class GridFixedWidth extends DataGridColumnWidth {
|
||||
const GridFixedWidth(this.width) : super._();
|
||||
final double width;
|
||||
}
|
||||
|
||||
/// Flexible column width.
|
||||
final class GridFlexWidth extends DataGridColumnWidth {
|
||||
const GridFlexWidth([this.flex = 1]) : super._();
|
||||
final int flex;
|
||||
}
|
||||
|
||||
/// Fractional column width.
|
||||
final class GridFractionWidth extends DataGridColumnWidth {
|
||||
const GridFractionWidth(this.fraction)
|
||||
: assert(fraction > 0 && fraction <= 1),
|
||||
super._();
|
||||
final double fraction;
|
||||
}
|
||||
|
||||
/// Column alignment options.
|
||||
enum DataGridColumnAlignment {
|
||||
start,
|
||||
center,
|
||||
end,
|
||||
}
|
||||
|
||||
/// Column definition for DataGrid.
|
||||
class DataGridColumn<T> {
|
||||
const DataGridColumn({
|
||||
required this.header,
|
||||
required this.valueBuilder,
|
||||
this.cellBuilder,
|
||||
this.cellControlsBuilder,
|
||||
this.width = const DataGridColumnWidth.flex(1),
|
||||
this.alignment = DataGridColumnAlignment.start,
|
||||
this.sortable = false,
|
||||
this.sortField,
|
||||
this.searchable = false,
|
||||
this.visible = true,
|
||||
this.tooltip,
|
||||
});
|
||||
|
||||
/// Column header text.
|
||||
final String header;
|
||||
|
||||
/// Extracts the string value from an item for sorting/searching.
|
||||
final String Function(T item) valueBuilder;
|
||||
|
||||
/// Custom cell widget builder. If null, displays valueBuilder result as text.
|
||||
final Widget Function(BuildContext context, T item)? cellBuilder;
|
||||
|
||||
/// Additional controls to show in the cell (e.g., quick actions).
|
||||
final Widget Function(BuildContext context, T item)? cellControlsBuilder;
|
||||
|
||||
/// Column width specification.
|
||||
final DataGridColumnWidth width;
|
||||
|
||||
/// Text alignment within the column.
|
||||
final DataGridColumnAlignment alignment;
|
||||
|
||||
/// Whether this column can be sorted.
|
||||
final bool sortable;
|
||||
|
||||
/// API field name for server-side sorting. Defaults to using header if null.
|
||||
final String? sortField;
|
||||
|
||||
/// Whether this column is included in search.
|
||||
final bool searchable;
|
||||
|
||||
/// Whether this column is visible.
|
||||
final bool visible;
|
||||
|
||||
/// Tooltip builder for cell hover.
|
||||
final String Function(T item)? tooltip;
|
||||
|
||||
/// Gets the effective sort field name.
|
||||
String get effectiveSortField => sortField ?? header.toLowerCase();
|
||||
|
||||
/// Converts alignment enum to CrossAxisAlignment.
|
||||
CrossAxisAlignment get crossAxisAlignment => switch (alignment) {
|
||||
DataGridColumnAlignment.start => CrossAxisAlignment.start,
|
||||
DataGridColumnAlignment.center => CrossAxisAlignment.center,
|
||||
DataGridColumnAlignment.end => CrossAxisAlignment.end,
|
||||
};
|
||||
|
||||
/// Converts alignment enum to TextAlign.
|
||||
TextAlign get textAlign => switch (alignment) {
|
||||
DataGridColumnAlignment.start => TextAlign.start,
|
||||
DataGridColumnAlignment.center => TextAlign.center,
|
||||
DataGridColumnAlignment.end => TextAlign.end,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'data_grid_action.dart';
|
||||
import 'data_grid_column.dart';
|
||||
|
||||
/// Data loading mode for the grid.
|
||||
sealed class DataGridDataMode {
|
||||
const DataGridDataMode._();
|
||||
|
||||
/// Load all data at once.
|
||||
const factory DataGridDataMode.all() = AllDataMode;
|
||||
|
||||
/// Paginated loading with page controls.
|
||||
const factory DataGridDataMode.paginated({int pageSize}) = PaginatedDataMode;
|
||||
|
||||
/// Infinite scroll loading.
|
||||
const factory DataGridDataMode.infinite({
|
||||
int initialLoad,
|
||||
int loadMoreThreshold,
|
||||
}) = InfiniteDataMode;
|
||||
}
|
||||
|
||||
/// Load all data mode.
|
||||
final class AllDataMode extends DataGridDataMode {
|
||||
const AllDataMode() : super._();
|
||||
}
|
||||
|
||||
/// Paginated data mode.
|
||||
final class PaginatedDataMode extends DataGridDataMode {
|
||||
const PaginatedDataMode({this.pageSize = 25}) : super._();
|
||||
final int pageSize;
|
||||
}
|
||||
|
||||
/// Infinite scroll data mode.
|
||||
final class InfiniteDataMode extends DataGridDataMode {
|
||||
const InfiniteDataMode({
|
||||
this.initialLoad = 50,
|
||||
this.loadMoreThreshold = 10,
|
||||
}) : super._();
|
||||
|
||||
final int initialLoad;
|
||||
final int loadMoreThreshold;
|
||||
}
|
||||
|
||||
/// Main configuration for a DataGrid.
|
||||
class DataGridConfig<T> {
|
||||
const DataGridConfig({
|
||||
required this.columns,
|
||||
this.actions = const [],
|
||||
this.bulkActions = const [],
|
||||
this.rowsSelectable = false,
|
||||
this.showHeader = true,
|
||||
this.showFooter = true,
|
||||
this.enableSearch = false,
|
||||
this.searchHint = 'Search...',
|
||||
this.defaultSortColumn,
|
||||
this.defaultSortDescending = false,
|
||||
this.emptyStateBuilder,
|
||||
this.loadingBuilder,
|
||||
this.errorBuilder,
|
||||
this.onRowTap,
|
||||
this.cellPadding = const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
this.headerHeight = 48.0,
|
||||
this.rowHeight,
|
||||
this.dataMode = const DataGridDataMode.all(),
|
||||
this.rowColor,
|
||||
this.alternatingRowColors = false,
|
||||
});
|
||||
|
||||
/// Column definitions.
|
||||
final List<DataGridColumn<T>> columns;
|
||||
|
||||
/// Per-row actions (shown in actions menu).
|
||||
final List<DataGridAction<T>> actions;
|
||||
|
||||
/// Bulk actions for selected rows.
|
||||
final List<DataGridBulkAction<T>> bulkActions;
|
||||
|
||||
/// Whether rows can be selected.
|
||||
final bool rowsSelectable;
|
||||
|
||||
/// Whether to show the header row.
|
||||
final bool showHeader;
|
||||
|
||||
/// Whether to show the footer with count/pagination.
|
||||
final bool showFooter;
|
||||
|
||||
/// Whether to show search bar.
|
||||
final bool enableSearch;
|
||||
|
||||
/// Placeholder text for search input.
|
||||
final String searchHint;
|
||||
|
||||
/// Index of column to sort by default.
|
||||
final int? defaultSortColumn;
|
||||
|
||||
/// Whether default sort is descending.
|
||||
final bool defaultSortDescending;
|
||||
|
||||
/// Custom empty state widget builder.
|
||||
final Widget Function(BuildContext context)? emptyStateBuilder;
|
||||
|
||||
/// Custom loading widget builder.
|
||||
final Widget Function(BuildContext context)? loadingBuilder;
|
||||
|
||||
/// Custom error widget builder.
|
||||
final Widget Function(BuildContext context, Object error, VoidCallback retry)?
|
||||
errorBuilder;
|
||||
|
||||
/// Callback when a row is tapped.
|
||||
final void Function(T item)? onRowTap;
|
||||
|
||||
/// Padding for each cell.
|
||||
final EdgeInsetsGeometry cellPadding;
|
||||
|
||||
/// Height of the header row.
|
||||
final double headerHeight;
|
||||
|
||||
/// Height of each data row. If null, rows size to content.
|
||||
final double? rowHeight;
|
||||
|
||||
/// Data loading mode.
|
||||
final DataGridDataMode dataMode;
|
||||
|
||||
/// Custom row background color builder.
|
||||
final Color? Function(BuildContext context, T item, int index)? rowColor;
|
||||
|
||||
/// Whether to use alternating row colors.
|
||||
final bool alternatingRowColors;
|
||||
|
||||
/// Gets visible columns only.
|
||||
List<DataGridColumn<T>> get visibleColumns =>
|
||||
columns.where((c) => c.visible).toList();
|
||||
|
||||
/// Gets searchable column indices.
|
||||
List<int> get searchableColumnIndices => columns
|
||||
.asMap()
|
||||
.entries
|
||||
.where((e) => e.value.searchable)
|
||||
.map((e) => e.key)
|
||||
.toList();
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/// DataGrid component for displaying tabular data.
|
||||
///
|
||||
/// This library provides a configurable, feature-rich data grid widget
|
||||
/// for Flutter applications using Riverpod for state management.
|
||||
///
|
||||
/// Features:
|
||||
/// - Sortable columns
|
||||
/// - Row selection (single and bulk)
|
||||
/// - Per-row and bulk actions with confirmations
|
||||
/// - Search/filtering
|
||||
/// - Pagination or infinite scroll
|
||||
/// - Custom cell rendering
|
||||
/// - Empty, loading, and error states
|
||||
/// - Responsive column widths
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// // Define your data source
|
||||
/// final usersSource = InMemoryDataSource<User>(
|
||||
/// items: users,
|
||||
/// searchMatcher: (user, query) =>
|
||||
/// user.name.toLowerCase().contains(query.toLowerCase()),
|
||||
/// );
|
||||
///
|
||||
/// // Define grid configuration
|
||||
/// final usersConfig = DataGridConfig<User>(
|
||||
/// columns: [
|
||||
/// DataGridColumn(
|
||||
/// header: 'Name',
|
||||
/// valueBuilder: (u) => u.name,
|
||||
/// sortable: true,
|
||||
/// searchable: true,
|
||||
/// ),
|
||||
/// DataGridColumn(
|
||||
/// header: 'Email',
|
||||
/// valueBuilder: (u) => u.email,
|
||||
/// ),
|
||||
/// DataGridColumn(
|
||||
/// header: 'Status',
|
||||
/// valueBuilder: (u) => u.status,
|
||||
/// cellBuilder: (context, u) => StatusBadge(status: u.status),
|
||||
/// ),
|
||||
/// ],
|
||||
/// actions: [
|
||||
/// DataGridAction(
|
||||
/// icon: Icons.edit,
|
||||
/// label: 'Edit',
|
||||
/// onTap: (user) async => editUser(user),
|
||||
/// ),
|
||||
/// DataGridAction(
|
||||
/// icon: Icons.delete,
|
||||
/// label: 'Delete',
|
||||
/// onTap: (user) async => deleteUser(user),
|
||||
/// destructive: true,
|
||||
/// requiresConfirmation: true,
|
||||
/// ),
|
||||
/// ],
|
||||
/// rowsSelectable: true,
|
||||
/// enableSearch: true,
|
||||
/// );
|
||||
///
|
||||
/// // Create the provider
|
||||
/// final usersGridProvider = dataGridProvider<User>(
|
||||
/// source: usersSource,
|
||||
/// config: usersConfig,
|
||||
/// idSelector: (u) => u.id,
|
||||
/// );
|
||||
///
|
||||
/// // Use in widget
|
||||
/// DataGrid<User>(
|
||||
/// provider: usersGridProvider,
|
||||
/// config: usersConfig,
|
||||
/// idSelector: (u) => u.id,
|
||||
/// )
|
||||
/// ```
|
||||
library;
|
||||
|
||||
export 'data_grid.dart';
|
||||
export 'data_grid_action.dart';
|
||||
export 'data_grid_column.dart';
|
||||
export 'data_grid_config.dart';
|
||||
export 'data_grid_provider.dart';
|
||||
export 'data_grid_source.dart';
|
||||
export 'data_grid_state.dart';
|
||||
export 'widgets/data_grid_empty_state.dart';
|
||||
@@ -0,0 +1,266 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'data_grid_config.dart';
|
||||
import 'data_grid_source.dart';
|
||||
import 'data_grid_state.dart';
|
||||
|
||||
/// Controller for a DataGrid instance.
|
||||
///
|
||||
/// Manages loading, searching, sorting, and selection state.
|
||||
class DataGridController<T> extends StateNotifier<DataGridState<T>> {
|
||||
DataGridController({
|
||||
required this.source,
|
||||
required this.config,
|
||||
required this.idSelector,
|
||||
}) : super(DataGridState<T>(
|
||||
sortColumnIndex: config.defaultSortColumn,
|
||||
sortDescending: config.defaultSortDescending,
|
||||
)) {
|
||||
// Initial load
|
||||
_load();
|
||||
}
|
||||
|
||||
/// Data source for fetching items.
|
||||
final DataGridSource<T> source;
|
||||
|
||||
/// Grid configuration.
|
||||
final DataGridConfig<T> config;
|
||||
|
||||
/// Function to extract unique ID from an item.
|
||||
final Object Function(T item) idSelector;
|
||||
|
||||
/// Debounce timer for search.
|
||||
Timer? _searchDebounce;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchDebounce?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Loads or reloads data from the source.
|
||||
Future<void> _load({bool refresh = false}) async {
|
||||
if (refresh) {
|
||||
state = state.copyWith(isLoading: true, error: null);
|
||||
} else {
|
||||
state = state.copyWith(isLoading: true, isInitialLoad: true, error: null);
|
||||
}
|
||||
|
||||
try {
|
||||
final sortField = state.sortColumnIndex != null
|
||||
? config.columns[state.sortColumnIndex!].effectiveSortField
|
||||
: null;
|
||||
|
||||
final (offset, limit) = _getPaginationParams();
|
||||
|
||||
final result = await source.fetch(
|
||||
searchQuery: state.searchQuery.isEmpty ? null : state.searchQuery,
|
||||
sortField: sortField,
|
||||
sortDescending: state.sortDescending,
|
||||
offset: offset,
|
||||
limit: limit,
|
||||
);
|
||||
|
||||
state = state.copyWith(
|
||||
items: result.items,
|
||||
totalCount: result.totalCount,
|
||||
hasMore: result.hasMore,
|
||||
isLoading: false,
|
||||
isInitialLoad: false,
|
||||
error: null,
|
||||
);
|
||||
} catch (e, stack) {
|
||||
debugPrint('DataGrid load error: $e\n$stack');
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
isInitialLoad: false,
|
||||
error: e,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets pagination parameters based on data mode.
|
||||
(int?, int?) _getPaginationParams() {
|
||||
return switch (config.dataMode) {
|
||||
AllDataMode() => (null, null),
|
||||
PaginatedDataMode(:final pageSize) => (
|
||||
state.currentPage * pageSize,
|
||||
pageSize,
|
||||
),
|
||||
InfiniteDataMode(:final initialLoad) => (0, initialLoad),
|
||||
};
|
||||
}
|
||||
|
||||
/// Refreshes the grid data.
|
||||
Future<void> refresh() => _load(refresh: true);
|
||||
|
||||
/// Sets the search query with debouncing.
|
||||
void search(String query) {
|
||||
_searchDebounce?.cancel();
|
||||
_searchDebounce = Timer(const Duration(milliseconds: 300), () {
|
||||
if (state.searchQuery != query) {
|
||||
state = state.copyWith(searchQuery: query, currentPage: 0);
|
||||
_load(refresh: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Clears the search query.
|
||||
void clearSearch() {
|
||||
_searchDebounce?.cancel();
|
||||
if (state.searchQuery.isNotEmpty) {
|
||||
state = state.copyWith(searchQuery: '', currentPage: 0);
|
||||
_load(refresh: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts by the given column index.
|
||||
void sortBy(int columnIndex) {
|
||||
final column = config.columns[columnIndex];
|
||||
if (!column.sortable) return;
|
||||
|
||||
final newDescending =
|
||||
state.sortColumnIndex == columnIndex ? !state.sortDescending : false;
|
||||
|
||||
state = state.copyWith(
|
||||
sortColumnIndex: columnIndex,
|
||||
sortDescending: newDescending,
|
||||
currentPage: 0,
|
||||
);
|
||||
_load(refresh: true);
|
||||
}
|
||||
|
||||
/// Clears sorting.
|
||||
void clearSort() {
|
||||
state = state.copyWith(
|
||||
sortColumnIndex: null,
|
||||
sortDescending: false,
|
||||
currentPage: 0,
|
||||
);
|
||||
_load(refresh: true);
|
||||
}
|
||||
|
||||
/// Toggles selection of an item.
|
||||
void toggleSelection(T item) {
|
||||
if (!config.rowsSelectable) return;
|
||||
|
||||
final id = idSelector(item);
|
||||
final newSelection = Set<Object>.from(state.selectedIds);
|
||||
|
||||
if (newSelection.contains(id)) {
|
||||
newSelection.remove(id);
|
||||
} else {
|
||||
newSelection.add(id);
|
||||
}
|
||||
|
||||
state = state.copyWith(selectedIds: newSelection);
|
||||
}
|
||||
|
||||
/// Selects all visible items.
|
||||
void selectAll() {
|
||||
if (!config.rowsSelectable) return;
|
||||
|
||||
final allIds = state.items.map(idSelector).toSet();
|
||||
state = state.copyWith(selectedIds: allIds);
|
||||
}
|
||||
|
||||
/// Clears all selections.
|
||||
void clearSelection() {
|
||||
state = state.copyWith(selectedIds: {});
|
||||
}
|
||||
|
||||
/// Toggles select all / clear all.
|
||||
void toggleSelectAll() {
|
||||
if (state.allSelected) {
|
||||
clearSelection();
|
||||
} else {
|
||||
selectAll();
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if an item is selected.
|
||||
bool isSelected(T item) => state.selectedIds.contains(idSelector(item));
|
||||
|
||||
/// Gets the selected items.
|
||||
List<T> getSelectedItems() {
|
||||
return state.items.where((item) => isSelected(item)).toList();
|
||||
}
|
||||
|
||||
/// Goes to a specific page (for paginated mode).
|
||||
void goToPage(int page) {
|
||||
if (config.dataMode is! PaginatedDataMode) return;
|
||||
|
||||
final mode = config.dataMode as PaginatedDataMode;
|
||||
final maxPage = (state.totalCount / mode.pageSize).ceil() - 1;
|
||||
|
||||
if (page < 0 || page > maxPage) return;
|
||||
|
||||
state = state.copyWith(currentPage: page);
|
||||
_load(refresh: true);
|
||||
}
|
||||
|
||||
/// Goes to the next page.
|
||||
void nextPage() => goToPage(state.currentPage + 1);
|
||||
|
||||
/// Goes to the previous page.
|
||||
void previousPage() => goToPage(state.currentPage - 1);
|
||||
|
||||
/// Loads more items (for infinite scroll mode).
|
||||
Future<void> loadMore() async {
|
||||
if (config.dataMode is! InfiniteDataMode) return;
|
||||
if (state.isLoading || !state.hasMore) return;
|
||||
|
||||
state = state.copyWith(isLoading: true);
|
||||
|
||||
try {
|
||||
final sortField = state.sortColumnIndex != null
|
||||
? config.columns[state.sortColumnIndex!].effectiveSortField
|
||||
: null;
|
||||
|
||||
final result = await source.fetch(
|
||||
searchQuery: state.searchQuery.isEmpty ? null : state.searchQuery,
|
||||
sortField: sortField,
|
||||
sortDescending: state.sortDescending,
|
||||
offset: state.items.length,
|
||||
limit: (config.dataMode as InfiniteDataMode).initialLoad,
|
||||
);
|
||||
|
||||
state = state.copyWith(
|
||||
items: [...state.items, ...result.items],
|
||||
totalCount: result.totalCount,
|
||||
hasMore: result.hasMore,
|
||||
isLoading: false,
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(isLoading: false, error: e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DataGridController provider for a specific grid.
|
||||
///
|
||||
/// Usage:
|
||||
/// ```dart
|
||||
/// final containersGridProvider = dataGridProvider<Container>(
|
||||
/// source: containersDataSource,
|
||||
/// config: containersGridConfig,
|
||||
/// idSelector: (c) => c.id,
|
||||
/// );
|
||||
/// ```
|
||||
StateNotifierProvider<DataGridController<T>, DataGridState<T>>
|
||||
dataGridProvider<T>({
|
||||
required DataGridSource<T> source,
|
||||
required DataGridConfig<T> config,
|
||||
required Object Function(T) idSelector,
|
||||
}) {
|
||||
return StateNotifierProvider<DataGridController<T>, DataGridState<T>>(
|
||||
(ref) => DataGridController<T>(
|
||||
source: source,
|
||||
config: config,
|
||||
idSelector: idSelector,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/// Result from a data source fetch operation.
|
||||
class DataGridResult<T> {
|
||||
const DataGridResult({
|
||||
required this.items,
|
||||
required this.totalCount,
|
||||
this.hasMore = false,
|
||||
});
|
||||
|
||||
/// The fetched items.
|
||||
final List<T> items;
|
||||
|
||||
/// Total count of items (for pagination display).
|
||||
final int totalCount;
|
||||
|
||||
/// Whether there are more items to load (for infinite scroll).
|
||||
final bool hasMore;
|
||||
|
||||
/// Creates an empty result.
|
||||
const DataGridResult.empty()
|
||||
: items = const [],
|
||||
totalCount = 0,
|
||||
hasMore = false;
|
||||
}
|
||||
|
||||
/// Abstract data source for DataGrid.
|
||||
///
|
||||
/// Implement this to provide data to the grid. Can be backed by
|
||||
/// API calls, local database, or in-memory lists.
|
||||
abstract class DataGridSource<T> {
|
||||
/// Fetches items from the data source.
|
||||
///
|
||||
/// - [searchQuery]: Optional search text to filter results.
|
||||
/// - [sortField]: Field name to sort by.
|
||||
/// - [sortDescending]: Whether to sort in descending order.
|
||||
/// - [offset]: Number of items to skip (for pagination).
|
||||
/// - [limit]: Maximum number of items to return.
|
||||
Future<DataGridResult<T>> fetch({
|
||||
String? searchQuery,
|
||||
String? sortField,
|
||||
bool sortDescending = false,
|
||||
int? offset,
|
||||
int? limit,
|
||||
});
|
||||
|
||||
/// Gets the total count of items matching the query.
|
||||
///
|
||||
/// Override this if you need a separate count query.
|
||||
/// By default, returns the totalCount from the last fetch.
|
||||
Future<int> count({String? searchQuery}) async {
|
||||
final result = await fetch(searchQuery: searchQuery, limit: 0);
|
||||
return result.totalCount;
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory data source for local data.
|
||||
class InMemoryDataSource<T> extends DataGridSource<T> {
|
||||
InMemoryDataSource({
|
||||
required this.items,
|
||||
this.searchMatcher,
|
||||
this.sortComparator,
|
||||
});
|
||||
|
||||
/// All items in the data source.
|
||||
final List<T> items;
|
||||
|
||||
/// Function to check if an item matches the search query.
|
||||
final bool Function(T item, String query)? searchMatcher;
|
||||
|
||||
/// Function to compare two items for sorting.
|
||||
final int Function(T a, T b, String field, bool descending)? sortComparator;
|
||||
|
||||
@override
|
||||
Future<DataGridResult<T>> fetch({
|
||||
String? searchQuery,
|
||||
String? sortField,
|
||||
bool sortDescending = false,
|
||||
int? offset,
|
||||
int? limit,
|
||||
}) async {
|
||||
var result = List<T>.from(items);
|
||||
|
||||
// Apply search filter
|
||||
if (searchQuery != null && searchQuery.isNotEmpty && searchMatcher != null) {
|
||||
result = result.where((item) => searchMatcher!(item, searchQuery)).toList();
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
if (sortField != null && sortComparator != null) {
|
||||
result.sort((a, b) => sortComparator!(a, b, sortField, sortDescending));
|
||||
}
|
||||
|
||||
final totalCount = result.length;
|
||||
|
||||
// Apply pagination
|
||||
if (offset != null && offset > 0) {
|
||||
result = result.skip(offset).toList();
|
||||
}
|
||||
if (limit != null && limit > 0) {
|
||||
result = result.take(limit).toList();
|
||||
}
|
||||
|
||||
return DataGridResult(
|
||||
items: result,
|
||||
totalCount: totalCount,
|
||||
hasMore: offset != null && limit != null && (offset + limit) < totalCount,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'data_grid_state.freezed.dart';
|
||||
|
||||
/// State for a DataGrid instance.
|
||||
@freezed
|
||||
class DataGridState<T> with _$DataGridState<T> {
|
||||
const factory DataGridState({
|
||||
/// Current items being displayed.
|
||||
@Default([]) List<T> items,
|
||||
|
||||
/// Total count of items (may differ from items.length for pagination).
|
||||
@Default(0) int totalCount,
|
||||
|
||||
/// Whether data is currently loading.
|
||||
@Default(false) bool isLoading,
|
||||
|
||||
/// Whether initial load is in progress.
|
||||
@Default(true) bool isInitialLoad,
|
||||
|
||||
/// Error that occurred during loading.
|
||||
Object? error,
|
||||
|
||||
/// Current search query.
|
||||
@Default('') String searchQuery,
|
||||
|
||||
/// Index of the column currently sorted by.
|
||||
int? sortColumnIndex,
|
||||
|
||||
/// Whether sort is descending.
|
||||
@Default(false) bool sortDescending,
|
||||
|
||||
/// Currently selected item IDs (if selectable).
|
||||
@Default({}) Set<Object> selectedIds,
|
||||
|
||||
/// Current page (for paginated mode).
|
||||
@Default(0) int currentPage,
|
||||
|
||||
/// Whether more items can be loaded (for infinite scroll).
|
||||
@Default(false) bool hasMore,
|
||||
}) = _DataGridState<T>;
|
||||
}
|
||||
|
||||
/// Extension methods for DataGridState.
|
||||
extension DataGridStateX<T> on DataGridState<T> {
|
||||
/// Whether the grid has an error.
|
||||
bool get hasError => error != null;
|
||||
|
||||
/// Whether the grid is empty (no items and not loading).
|
||||
bool get isEmpty => items.isEmpty && !isLoading && !hasError;
|
||||
|
||||
/// Whether all visible items are selected.
|
||||
bool get allSelected =>
|
||||
items.isNotEmpty && selectedIds.length == items.length;
|
||||
|
||||
/// Whether some (but not all) items are selected.
|
||||
bool get someSelected =>
|
||||
selectedIds.isNotEmpty && selectedIds.length < items.length;
|
||||
|
||||
/// Number of selected items.
|
||||
int get selectedCount => selectedIds.length;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data_grid_action.dart';
|
||||
|
||||
/// Actions menu for a DataGrid row.
|
||||
class DataGridActionsMenu<T> extends StatelessWidget {
|
||||
const DataGridActionsMenu({
|
||||
super.key,
|
||||
required this.item,
|
||||
required this.actions,
|
||||
});
|
||||
|
||||
final T item;
|
||||
final List<DataGridAction<T>> actions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visibleActions = actions.where((a) => a.shouldShow(item)).toList();
|
||||
|
||||
if (visibleActions.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return PopupMenuButton<DataGridAction<T>>(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
tooltip: 'Actions',
|
||||
onSelected: (action) => _handleAction(context, action),
|
||||
itemBuilder: (context) => visibleActions.map((action) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return PopupMenuItem<DataGridAction<T>>(
|
||||
value: action,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
action.icon,
|
||||
size: 20,
|
||||
color: action.destructive ? colorScheme.error : null,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
action.label,
|
||||
style: TextStyle(
|
||||
color: action.destructive ? colorScheme.error : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleAction(
|
||||
BuildContext context,
|
||||
DataGridAction<T> action,
|
||||
) async {
|
||||
if (action.requiresConfirmation) {
|
||||
final confirmed = await _showConfirmationDialog(context, action);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
|
||||
await action.onTap(item);
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmationDialog(
|
||||
BuildContext context,
|
||||
DataGridAction<T> action,
|
||||
) async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(action.label),
|
||||
content: Text(
|
||||
action.confirmationMessage ?? 'Are you sure you want to proceed?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
style: action.destructive
|
||||
? FilledButton.styleFrom(
|
||||
backgroundColor: colorScheme.error,
|
||||
foregroundColor: colorScheme.onError,
|
||||
)
|
||||
: null,
|
||||
child: const Text('Confirm'),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data_grid_action.dart';
|
||||
|
||||
/// Bulk actions bar shown when items are selected.
|
||||
class DataGridBulkActions<T> extends StatelessWidget {
|
||||
const DataGridBulkActions({
|
||||
super.key,
|
||||
required this.selectedCount,
|
||||
required this.bulkActions,
|
||||
required this.onClearSelection,
|
||||
required this.getSelectedItems,
|
||||
});
|
||||
|
||||
final int selectedCount;
|
||||
final List<DataGridBulkAction<T>> bulkActions;
|
||||
final VoidCallback onClearSelection;
|
||||
final List<T> Function() getSelectedItems;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'$selectedCount selected',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w500,
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
...bulkActions.where((a) => a.isAvailable(selectedCount)).map(
|
||||
(action) => Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: _BulkActionButton(
|
||||
action: action,
|
||||
onPressed: () => _handleAction(context, action),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: onClearSelection,
|
||||
tooltip: 'Clear selection',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleAction(
|
||||
BuildContext context,
|
||||
DataGridBulkAction<T> action,
|
||||
) async {
|
||||
if (action.requiresConfirmation) {
|
||||
final confirmed = await _showConfirmationDialog(context, action);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
|
||||
final items = getSelectedItems();
|
||||
await action.onTap(items);
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmationDialog(
|
||||
BuildContext context,
|
||||
DataGridBulkAction<T> action,
|
||||
) async {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(action.label),
|
||||
content: Text(
|
||||
action.confirmationMessage ??
|
||||
'Are you sure you want to ${action.label.toLowerCase()} $selectedCount items?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
style: action.destructive
|
||||
? FilledButton.styleFrom(
|
||||
backgroundColor: colorScheme.error,
|
||||
foregroundColor: colorScheme.onError,
|
||||
)
|
||||
: null,
|
||||
child: const Text('Confirm'),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
}
|
||||
|
||||
class _BulkActionButton<T> extends StatelessWidget {
|
||||
const _BulkActionButton({
|
||||
required this.action,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final DataGridBulkAction<T> action;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
if (action.destructive) {
|
||||
return OutlinedButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(action.icon, size: 18),
|
||||
label: Text(action.label),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: colorScheme.error,
|
||||
side: BorderSide(color: colorScheme.error),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return OutlinedButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(action.icon, size: 18),
|
||||
label: Text(action.label),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: colorScheme.onPrimaryContainer,
|
||||
side: BorderSide(color: colorScheme.onPrimaryContainer),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Default empty state for DataGrid.
|
||||
class DataGridEmptyState extends StatelessWidget {
|
||||
const DataGridEmptyState({
|
||||
super.key,
|
||||
this.icon = Icons.inbox_outlined,
|
||||
this.title = 'No items found',
|
||||
this.subtitle,
|
||||
this.action,
|
||||
this.onAction,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final String? action;
|
||||
final VoidCallback? onAction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 64,
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
if (subtitle != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
subtitle!,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
if (action != null && onAction != null) ...[
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.tonal(
|
||||
onPressed: onAction,
|
||||
child: Text(action!),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Loading state for DataGrid.
|
||||
class DataGridLoadingState extends StatelessWidget {
|
||||
const DataGridLoadingState({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(32),
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Error state for DataGrid.
|
||||
class DataGridErrorState extends StatelessWidget {
|
||||
const DataGridErrorState({
|
||||
super.key,
|
||||
required this.error,
|
||||
required this.onRetry,
|
||||
});
|
||||
|
||||
final Object error;
|
||||
final VoidCallback onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 64,
|
||||
color: colorScheme.error,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Failed to load data',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
error.toString(),
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.outline,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data_grid_config.dart';
|
||||
|
||||
/// Footer for DataGrid with item count and pagination controls.
|
||||
class DataGridFooter extends StatelessWidget {
|
||||
const DataGridFooter({
|
||||
super.key,
|
||||
required this.totalCount,
|
||||
required this.displayedCount,
|
||||
required this.dataMode,
|
||||
this.currentPage = 0,
|
||||
this.onPageChange,
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
final int totalCount;
|
||||
final int displayedCount;
|
||||
final DataGridDataMode dataMode;
|
||||
final int currentPage;
|
||||
final void Function(int page)? onPageChange;
|
||||
final bool isLoading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
border: Border(
|
||||
top: BorderSide(color: colorScheme.outlineVariant),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
_getCountText(),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (dataMode is PaginatedDataMode) _buildPaginationControls(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _getCountText() {
|
||||
return switch (dataMode) {
|
||||
AllDataMode() => '$totalCount items',
|
||||
PaginatedDataMode(:final pageSize) => _getPaginatedCountText(pageSize),
|
||||
InfiniteDataMode() => '$displayedCount of $totalCount items',
|
||||
};
|
||||
}
|
||||
|
||||
String _getPaginatedCountText(int pageSize) {
|
||||
final start = currentPage * pageSize + 1;
|
||||
final end = (start + displayedCount - 1).clamp(start, totalCount);
|
||||
return '$start-$end of $totalCount items';
|
||||
}
|
||||
|
||||
Widget _buildPaginationControls(BuildContext context) {
|
||||
final mode = dataMode as PaginatedDataMode;
|
||||
final totalPages = (totalCount / mode.pageSize).ceil();
|
||||
final canGoPrevious = currentPage > 0;
|
||||
final canGoNext = currentPage < totalPages - 1;
|
||||
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.first_page),
|
||||
onPressed: canGoPrevious ? () => onPageChange?.call(0) : null,
|
||||
tooltip: 'First page',
|
||||
iconSize: 20,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_left),
|
||||
onPressed:
|
||||
canGoPrevious ? () => onPageChange?.call(currentPage - 1) : null,
|
||||
tooltip: 'Previous page',
|
||||
iconSize: 20,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Text(
|
||||
'Page ${currentPage + 1} of $totalPages',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_right),
|
||||
onPressed:
|
||||
canGoNext ? () => onPageChange?.call(currentPage + 1) : null,
|
||||
tooltip: 'Next page',
|
||||
iconSize: 20,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.last_page),
|
||||
onPressed:
|
||||
canGoNext ? () => onPageChange?.call(totalPages - 1) : null,
|
||||
tooltip: 'Last page',
|
||||
iconSize: 20,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data_grid_column.dart';
|
||||
import '../data_grid_config.dart';
|
||||
|
||||
/// Header row for DataGrid.
|
||||
class DataGridHeader<T> extends StatelessWidget {
|
||||
const DataGridHeader({
|
||||
super.key,
|
||||
required this.config,
|
||||
required this.sortColumnIndex,
|
||||
required this.sortDescending,
|
||||
required this.onSort,
|
||||
this.showCheckbox = false,
|
||||
this.allSelected = false,
|
||||
this.someSelected = false,
|
||||
this.onSelectAll,
|
||||
});
|
||||
|
||||
final DataGridConfig<T> config;
|
||||
final int? sortColumnIndex;
|
||||
final bool sortDescending;
|
||||
final void Function(int columnIndex) onSort;
|
||||
final bool showCheckbox;
|
||||
final bool allSelected;
|
||||
final bool someSelected;
|
||||
final VoidCallback? onSelectAll;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final columns = config.visibleColumns;
|
||||
|
||||
return Container(
|
||||
height: config.headerHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
border: Border(
|
||||
bottom: BorderSide(color: colorScheme.outlineVariant),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
if (showCheckbox)
|
||||
SizedBox(
|
||||
width: 56,
|
||||
child: Center(
|
||||
child: Checkbox(
|
||||
value: allSelected ? true : (someSelected ? null : false),
|
||||
tristate: true,
|
||||
onChanged: (_) => onSelectAll?.call(),
|
||||
),
|
||||
),
|
||||
),
|
||||
...columns.asMap().entries.map((entry) {
|
||||
final index = entry.key;
|
||||
final column = entry.value;
|
||||
final isSorted = sortColumnIndex == index;
|
||||
|
||||
return _buildHeaderCell(
|
||||
context,
|
||||
column,
|
||||
index,
|
||||
isSorted,
|
||||
isSorted && sortDescending,
|
||||
);
|
||||
}),
|
||||
if (config.actions.isNotEmpty)
|
||||
const SizedBox(width: 56), // Space for actions column
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeaderCell(
|
||||
BuildContext context,
|
||||
DataGridColumn<T> column,
|
||||
int index,
|
||||
bool isSorted,
|
||||
bool isDescending,
|
||||
) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final textStyle = Theme.of(context).textTheme.labelLarge?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
);
|
||||
|
||||
Widget content = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
column.header,
|
||||
style: textStyle,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: column.textAlign,
|
||||
),
|
||||
),
|
||||
if (column.sortable) ...[
|
||||
const SizedBox(width: 4),
|
||||
AnimatedRotation(
|
||||
turns: isDescending ? 0.5 : 0,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: Icon(
|
||||
isSorted ? Icons.arrow_upward : Icons.unfold_more,
|
||||
size: 16,
|
||||
color: isSorted
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
if (column.sortable) {
|
||||
content = InkWell(
|
||||
onTap: () => onSort(index),
|
||||
child: Padding(
|
||||
padding: config.cellPadding,
|
||||
child: content,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
content = Padding(
|
||||
padding: config.cellPadding,
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
|
||||
return _wrapWithWidth(column.width, content);
|
||||
}
|
||||
|
||||
Widget _wrapWithWidth(DataGridColumnWidth width, Widget child) {
|
||||
return switch (width) {
|
||||
GridFixedWidth(:final width) => SizedBox(width: width, child: child),
|
||||
GridFlexWidth(:final flex) => Expanded(flex: flex, child: child),
|
||||
GridFractionWidth(:final fraction) => FractionallySizedBox(
|
||||
widthFactor: fraction,
|
||||
child: child,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data_grid_column.dart';
|
||||
import '../data_grid_config.dart';
|
||||
import 'data_grid_actions_menu.dart';
|
||||
|
||||
/// A single data row in the DataGrid.
|
||||
class DataGridRow<T> extends StatelessWidget {
|
||||
const DataGridRow({
|
||||
super.key,
|
||||
required this.item,
|
||||
required this.index,
|
||||
required this.config,
|
||||
this.isSelected = false,
|
||||
this.onSelect,
|
||||
this.onTap,
|
||||
this.backgroundColor,
|
||||
});
|
||||
|
||||
final T item;
|
||||
final int index;
|
||||
final DataGridConfig<T> config;
|
||||
final bool isSelected;
|
||||
final VoidCallback? onSelect;
|
||||
final VoidCallback? onTap;
|
||||
final Color? backgroundColor;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final columns = config.visibleColumns;
|
||||
|
||||
// Determine row background color
|
||||
Color? bgColor = backgroundColor;
|
||||
if (bgColor == null && config.alternatingRowColors) {
|
||||
bgColor = index.isOdd
|
||||
? colorScheme.surfaceContainerLowest
|
||||
: colorScheme.surface;
|
||||
}
|
||||
if (isSelected) {
|
||||
bgColor = colorScheme.primaryContainer.withValues(alpha: 0.3);
|
||||
}
|
||||
|
||||
final rowContent = Container(
|
||||
height: config.rowHeight,
|
||||
constraints: config.rowHeight == null
|
||||
? const BoxConstraints(minHeight: 48)
|
||||
: null,
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
border: Border(
|
||||
bottom: BorderSide(
|
||||
color: colorScheme.outlineVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
if (config.rowsSelectable)
|
||||
SizedBox(
|
||||
width: 56,
|
||||
child: Center(
|
||||
child: Checkbox(
|
||||
value: isSelected,
|
||||
onChanged: (_) => onSelect?.call(),
|
||||
),
|
||||
),
|
||||
),
|
||||
...columns.map((column) => _buildCell(context, column)),
|
||||
if (config.actions.isNotEmpty)
|
||||
SizedBox(
|
||||
width: 56,
|
||||
child: DataGridActionsMenu<T>(
|
||||
item: item,
|
||||
actions: config.actions,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (onTap != null) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: rowContent,
|
||||
);
|
||||
}
|
||||
|
||||
return rowContent;
|
||||
}
|
||||
|
||||
Widget _buildCell(BuildContext context, DataGridColumn<T> column) {
|
||||
Widget content;
|
||||
|
||||
if (column.cellBuilder != null) {
|
||||
content = column.cellBuilder!(context, item);
|
||||
} else {
|
||||
content = Text(
|
||||
column.valueBuilder(item),
|
||||
textAlign: column.textAlign,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
);
|
||||
}
|
||||
|
||||
// Wrap with controls if provided
|
||||
if (column.cellControlsBuilder != null) {
|
||||
content = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(child: content),
|
||||
const SizedBox(width: 8),
|
||||
column.cellControlsBuilder!(context, item),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Wrap with tooltip if provided
|
||||
if (column.tooltip != null) {
|
||||
content = Tooltip(
|
||||
message: column.tooltip!(item),
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
|
||||
final cell = Padding(
|
||||
padding: config.cellPadding,
|
||||
child: Align(
|
||||
alignment: switch (column.alignment) {
|
||||
DataGridColumnAlignment.start => Alignment.centerLeft,
|
||||
DataGridColumnAlignment.center => Alignment.center,
|
||||
DataGridColumnAlignment.end => Alignment.centerRight,
|
||||
},
|
||||
child: content,
|
||||
),
|
||||
);
|
||||
|
||||
return _wrapWithWidth(column.width, cell);
|
||||
}
|
||||
|
||||
Widget _wrapWithWidth(DataGridColumnWidth width, Widget child) {
|
||||
return switch (width) {
|
||||
GridFixedWidth(:final width) => SizedBox(width: width, child: child),
|
||||
GridFlexWidth(:final flex) => Expanded(flex: flex, child: child),
|
||||
GridFractionWidth(:final fraction) => FractionallySizedBox(
|
||||
widthFactor: fraction,
|
||||
child: child,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Search bar for DataGrid.
|
||||
class DataGridSearchBar extends StatefulWidget {
|
||||
const DataGridSearchBar({
|
||||
super.key,
|
||||
required this.onSearch,
|
||||
required this.onClear,
|
||||
this.hintText = 'Search...',
|
||||
this.initialValue = '',
|
||||
});
|
||||
|
||||
final void Function(String query) onSearch;
|
||||
final VoidCallback onClear;
|
||||
final String hintText;
|
||||
final String initialValue;
|
||||
|
||||
@override
|
||||
State<DataGridSearchBar> createState() => _DataGridSearchBarState();
|
||||
}
|
||||
|
||||
class _DataGridSearchBarState extends State<DataGridSearchBar> {
|
||||
late final TextEditingController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = TextEditingController(text: widget.initialValue);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return SizedBox(
|
||||
width: 300,
|
||||
child: TextField(
|
||||
controller: _controller,
|
||||
decoration: InputDecoration(
|
||||
hintText: widget.hintText,
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: _controller.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
_controller.clear();
|
||||
widget.onClear();
|
||||
},
|
||||
)
|
||||
: null,
|
||||
isDense: true,
|
||||
filled: true,
|
||||
fillColor: colorScheme.surfaceContainerHighest,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
onChanged: (value) {
|
||||
setState(() {}); // Update clear button visibility
|
||||
widget.onSearch(value);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user