Files
flutter/lib/features/nutrition/widgets/widgets.dart
2026-09-26 22:38:40 +02:00

354 lines
13 KiB
Dart

/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2020 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:logging/logging.dart';
import 'package:material_ui/material_ui.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/platform.dart';
import 'package:wger/core/search_options.dart';
import 'package:wger/core/widgets/core.dart';
import 'package:wger/core/widgets/legacy_material_scope.dart';
import 'package:wger/core/widgets/wger_image.dart';
import 'package:wger/features/nutrition/models/ingredient.dart';
import 'package:wger/features/nutrition/providers/ingredient_filters_notifier.dart';
import 'package:wger/features/nutrition/providers/ingredient_repository.dart';
import 'package:wger/features/nutrition/widgets/helpers.dart';
import 'package:wger/features/nutrition/widgets/ingredient_dialogs.dart';
import 'package:wger/features/nutrition/widgets/ingredient_filter_dialog.dart';
import 'package:wger/features/nutrition/widgets/nutri_score_badge.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
class ScanReader extends StatelessWidget {
const ScanReader();
@override
Widget build(BuildContext context) => Scaffold(
body: LegacyMaterialScope(
child: ReaderWidget(
onScan: (result) {
// notes:
// 1. even if result.isValid, result.error is always non-null (and set to "")
// 2. i've never encountered scan errors to see when they occur, and
// i wouldn't know what to do about them anyway, so we simply return
// result.text in such case (which presumably will be null, or "")
// 3. when user cancels (swipe left / back button) this code is no longer
// run and the caller receives null
Navigator.pop(context, result.text);
},
),
),
);
}
class IngredientTypeahead extends ConsumerStatefulWidget {
final _logger = Logger('IngredientTypeahead');
final TextEditingController _ingredientController;
final TextEditingController _ingredientIdController;
final String barcode;
final bool test;
final bool showScanner;
final Function(Ingredient ingredient, num? amount) selectIngredient;
final Function() onDeselectIngredient;
final Function(String query) onUpdateSearchQuery;
IngredientTypeahead(
this._ingredientIdController,
this._ingredientController, {
this.showScanner = true,
this.test = false,
this.barcode = '',
required this.selectIngredient,
required this.onDeselectIngredient,
required this.onUpdateSearchQuery,
});
@override
ConsumerState<IngredientTypeahead> createState() => _IngredientTypeaheadState();
}
class _IngredientTypeaheadState extends ConsumerState<IngredientTypeahead> {
late String barcode;
@override
void initState() {
super.initState();
barcode = widget.barcode; // for unit tests
}
Future<String> openBarcodeScan(BuildContext context) async {
try {
final code = await Navigator.of(
context,
).push<String?>(MaterialPageRoute(builder: (context) => const ScanReader()));
// A decoder that never returns looks exactly like a cancelled scan from
// here, so log the empty result as the only trace it leaves.
if (code == null || code.isEmpty || code == '-1') {
widget._logger.info('Barcode scanner returned no code');
return '';
}
return code;
} on PlatformException catch (e) {
widget._logger.warning('PlatformException during barcode scan: $e');
return '';
}
}
@override
Widget build(BuildContext context) {
final filters = ref.watch(ingredientFiltersSyncProvider);
final isOnline = ref.watch(networkStatusProvider);
return Column(
children: [
TypeAheadField<Ingredient>(
controller: widget._ingredientController,
debounceDuration: const Duration(milliseconds: 500),
builder: (context, controller, focusNode) {
return TextFormField(
controller: controller,
focusNode: focusNode,
autofocus: true,
validator: (value) {
// Require an actual selection; typed-but-unpicked text leaves the
// id empty and would crash the submit's int.parse on the id.
if (value == null || value.isEmpty || widget._ingredientIdController.text.isEmpty) {
return AppLocalizations.of(context).selectIngredient;
}
return null;
},
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
labelText: AppLocalizations.of(context).searchIngredient,
suffixIcon: Row(
mainAxisSize: MainAxisSize.min,
children: [
filterButton(),
if (widget.showScanner && !isDesktop && isOnline) scanButton(),
],
),
),
);
},
suggestionsCallback: (pattern) {
// don't do search if user has already loaded a specific item
if (pattern == '' || widget._ingredientIdController.text.isNotEmpty) {
return null;
}
widget.onUpdateSearchQuery(pattern);
widget.onDeselectIngredient();
// The repository picks the REST or the local-DB path based on
// current connectivity.
return ref
.read(ingredientRepositoryProvider)
.search(
pattern,
isOnline: ref.read(networkStatusProvider),
languageCode: Localizations.localeOf(context).languageCode,
searchLanguage: filters.searchLanguage,
isVegan: filters.isVegan,
isVegetarian: filters.isVegetarian,
nutriscoreMax: filters.nutriscoreMax,
);
},
itemBuilder: (context, ingredient) {
final i18n = AppLocalizations.of(context);
final chips = <Widget>[];
if (ingredient.isVegan == true) {
chips.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.green[100],
borderRadius: BorderRadius.circular(8),
),
child: Text(
i18n.isVegan,
style: TextStyle(fontSize: 11, color: Colors.green[900]),
),
),
);
} else if (ingredient.isVegetarian == true) {
chips.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.green[100],
borderRadius: BorderRadius.circular(8),
),
child: Text(
i18n.isVegetarian,
style: TextStyle(fontSize: 11, color: Colors.green[900]),
),
),
);
}
if (ingredient.nutriscore != null) {
chips.add(NutriScoreBadge(score: ingredient.nutriscore!, size: NutriScoreSize.small));
}
return ListTile(
leading: WgerImage(
mediaPath: ingredient.image?.image,
width: 40,
height: 40,
cacheWidth: 120,
borderRadius: BorderRadius.circular(20),
errorWidget: const CircleIconAvatar(
Icon(Icons.image, color: Colors.grey),
),
),
title: Text.rich(
TextSpan(
children: [
TextSpan(text: ingredient.name),
if (ingredient.brand case final brand? when brand.isNotEmpty)
TextSpan(
text: ' $brand',
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant.withValues(alpha: 0.7),
),
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
subtitle: chips.isNotEmpty ? Wrap(spacing: 4, runSpacing: 4, children: chips) : null,
trailing: IconButton(
icon: const Icon(Icons.info_outline),
onPressed: () {
showIngredientDetails(
context,
ref,
ingredient,
select: () {
widget.selectIngredient(ingredient, null);
},
);
},
),
);
},
transitionBuilder: (context, animation, child) => FadeTransition(
opacity: CurvedAnimation(parent: animation, curve: Curves.fastOutSlowIn),
child: child,
),
onSelected: (suggestion) async {
widget.selectIngredient(suggestion, null);
},
),
],
);
}
Widget scanButton() {
return IconButton(
key: const Key('scan-button'),
tooltip: AppLocalizations.of(context).scanBarcode,
icon: const FaIcon(FontAwesomeIcons.barcode),
onPressed: () async {
if (!widget.test) {
barcode = await openBarcodeScan(context);
}
if (!mounted) {
return;
}
// Started in the tap handler: reading a provider in the route builder
// runs during build, and an inline future re-fires on every rebuild.
final search = ref.read(ingredientRepositoryProvider).searchIngredientByBarcode(barcode);
showDialog(
context: context,
builder: (context) => FutureBuilder<Ingredient?>(
future: search,
builder: (BuildContext context, AsyncSnapshot<Ingredient?> snapshot) {
return IngredientScanResultDialog(snapshot, barcode, widget.selectIngredient);
},
),
);
},
);
}
/// The filter icon button, shows an active-filter badge and opens
/// [IngredientFilterDialog] on tap.
Widget filterButton() {
final filters = ref.watch(ingredientFiltersSyncProvider);
final languageCode = Localizations.localeOf(context).languageCode;
// Auto-correct: in an English locale "current + English" collapses to
// "current", fix it once if a stored preference landed on the
// non-locale-aware default.
if (languageCode == LANGUAGE_SHORT_ENGLISH &&
filters.searchLanguage == SearchLanguage.currentAndEnglish) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(ingredientFiltersProvider.notifier).chooseLanguage(SearchLanguage.current);
});
}
final activeFilterCount = filters.activeFilterCount(languageCode);
return IconButton(
icon: Badge(
label: Text('$activeFilterCount'),
isLabelVisible: activeFilterCount > 0,
child: const Icon(Icons.tune),
),
onPressed: () => showDialog(
context: context,
builder: (_) => const IngredientFilterDialog(),
),
);
}
}
class IngredientAvatar extends ConsumerWidget {
final Ingredient ingredient;
const IngredientAvatar({super.key, required this.ingredient});
@override
Widget build(BuildContext context, WidgetRef ref) {
final image = WgerImage(
mediaPath: ingredient.image?.image,
width: 40,
height: 40,
cacheWidth: 120,
borderRadius: BorderRadius.circular(20),
errorWidget: const CircleIconAvatar(Icon(Icons.image, color: Colors.grey)),
);
return GestureDetector(
onTap: () => showIngredientDetails(context, ref, ingredient),
child: image,
);
}
}