Add overview screen and serialization files for nutritional plans

This commit is contained in:
Roland Geider
2020-11-18 23:25:56 +01:00
parent 5115e4726e
commit 31af3bf95f
17 changed files with 485 additions and 18 deletions

View File

@@ -3,6 +3,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:wger/locale/locales.dart';
import 'package:wger/providers/exercises.dart';
import 'package:wger/providers/nutritional_plans.dart';
import 'package:wger/providers/workout_plans.dart';
import 'package:wger/screens/auth_screen.dart';
import 'package:wger/screens/dashboard.dart';
@@ -45,6 +46,13 @@ class MyApp extends StatelessWidget {
auth,
previous == null ? [] : previous.items,
),
),
ChangeNotifierProxyProvider<Auth, NutritionalPlans>(
create: null, // TODO: Create is required but it can be null??
update: (context, value, previous) => NutritionalPlans(
auth,
previous == null ? [] : previous.items,
),
)
],
child: MaterialApp(

View File

@@ -1,14 +1,35 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
part 'ingredient.g.dart';
@JsonSerializable()
class Ingredient {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String name;
@JsonKey(required: true, name: 'creation_date')
final DateTime creationDate;
@JsonKey(required: true)
final int energy;
@JsonKey(required: true)
final double carbohydrates;
@JsonKey(required: true)
final double carbohydrates_sugar;
@JsonKey(required: true)
final double fat;
@JsonKey(required: true)
final double fat_saturated;
@JsonKey(required: true)
final double fibres;
Ingredient({
@@ -22,4 +43,8 @@ class Ingredient {
@required this.fat_saturated,
@required this.fibres,
});
// Boilerplate
factory Ingredient.fromJson(Map<String, dynamic> json) => _$IngredientFromJson(json);
Map<String, dynamic> toJson() => _$IngredientToJson(this);
}

View File

@@ -0,0 +1,47 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'ingredient.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Ingredient _$IngredientFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const [
'id',
'name',
'creation_date',
'energy',
'carbohydrates',
'carbohydrates_sugar',
'fat',
'fat_saturated',
'fibres'
]);
return Ingredient(
id: json['id'] as int,
name: json['name'] as String,
creationDate: json['creation_date'] == null
? null
: DateTime.parse(json['creation_date'] as String),
energy: json['energy'] as int,
carbohydrates: (json['carbohydrates'] as num)?.toDouble(),
carbohydrates_sugar: (json['carbohydrates_sugar'] as num)?.toDouble(),
fat: (json['fat'] as num)?.toDouble(),
fat_saturated: (json['fat_saturated'] as num)?.toDouble(),
fibres: (json['fibres'] as num)?.toDouble(),
);
}
Map<String, dynamic> _$IngredientToJson(Ingredient instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'creation_date': instance.creationDate?.toIso8601String(),
'energy': instance.energy,
'carbohydrates': instance.carbohydrates,
'carbohydrates_sugar': instance.carbohydrates_sugar,
'fat': instance.fat,
'fat_saturated': instance.fat_saturated,
'fibres': instance.fibres,
};

View File

@@ -1,12 +1,25 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/weight_unit.dart';
part 'ingredient_weight_unit.g.dart';
@JsonSerializable()
class IngredientWeightUnit {
@JsonKey(required: true)
final int id;
final Ingredient weightUnit;
final WeightUnit ingredient;
@JsonKey(required: true, name: 'weight_unit')
final WeightUnit weightUnit;
@JsonKey(required: true)
final Ingredient ingredient;
@JsonKey(required: true)
final int grams;
@JsonKey(required: true)
final double amount;
IngredientWeightUnit({
@@ -16,4 +29,9 @@ class IngredientWeightUnit {
@required this.grams,
@required this.amount,
});
// Boilerplate
factory IngredientWeightUnit.fromJson(Map<String, dynamic> json) =>
_$IngredientWeightUnitFromJson(json);
Map<String, dynamic> toJson() => _$IngredientWeightUnitToJson(this);
}

View File

@@ -0,0 +1,38 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'ingredient_weight_unit.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
IngredientWeightUnit _$IngredientWeightUnitFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const [
'id',
'weight_unit',
'ingredient',
'grams',
'amount'
]);
return IngredientWeightUnit(
id: json['id'] as int,
weightUnit: json['weight_unit'] == null
? null
: WeightUnit.fromJson(json['weight_unit'] as Map<String, dynamic>),
ingredient: json['ingredient'] == null
? null
: Ingredient.fromJson(json['ingredient'] as Map<String, dynamic>),
grams: json['grams'] as int,
amount: (json['amount'] as num)?.toDouble(),
);
}
Map<String, dynamic> _$IngredientWeightUnitToJson(
IngredientWeightUnit instance) =>
<String, dynamic>{
'id': instance.id,
'weight_unit': instance.weightUnit,
'ingredient': instance.ingredient,
'grams': instance.grams,
'amount': instance.amount,
};

View File

@@ -1,14 +1,26 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/nutrition/meal_item.dart';
part 'meal.g.dart';
@JsonSerializable()
class Meal {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final DateTime time;
@JsonKey(required: true, name: 'meal_items')
final List<MealItem> mealItems;
Meal({
@required this.id,
@required this.time,
@required this.mealItems,
this.id,
this.time,
this.mealItems,
});
// Boilerplate
factory Meal.fromJson(Map<String, dynamic> json) => _$MealFromJson(json);
Map<String, dynamic> toJson() => _$MealToJson(this);
}

View File

@@ -0,0 +1,25 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'meal.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Meal _$MealFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const ['id', 'time', 'meal_items']);
return Meal(
id: json['id'] as int,
time: json['time'] == null ? null : DateTime.parse(json['time'] as String),
mealItems: (json['meal_items'] as List)
?.map((e) =>
e == null ? null : MealItem.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$MealToJson(Meal instance) => <String, dynamic>{
'id': instance.id,
'time': instance.time?.toIso8601String(),
'meal_items': instance.mealItems,
};

View File

@@ -1,11 +1,22 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/ingredient_weight_unit.dart';
part 'meal_item.g.dart';
@JsonSerializable()
class MealItem {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final Ingredient ingredient;
@JsonKey(required: true)
final IngredientWeightUnit weightUnit;
@JsonKey(required: true)
final double amount;
MealItem({
@@ -14,4 +25,8 @@ class MealItem {
@required this.weightUnit,
@required this.amount,
});
// Boilerplate
factory MealItem.fromJson(Map<String, dynamic> json) => _$MealItemFromJson(json);
Map<String, dynamic> toJson() => _$MealItemToJson(this);
}

View File

@@ -0,0 +1,30 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'meal_item.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MealItem _$MealItemFromJson(Map<String, dynamic> json) {
$checkKeys(json,
requiredKeys: const ['id', 'ingredient', 'weightUnit', 'amount']);
return MealItem(
id: json['id'] as int,
ingredient: json['ingredient'] == null
? null
: Ingredient.fromJson(json['ingredient'] as Map<String, dynamic>),
weightUnit: json['weightUnit'] == null
? null
: IngredientWeightUnit.fromJson(
json['weightUnit'] as Map<String, dynamic>),
amount: (json['amount'] as num)?.toDouble(),
);
}
Map<String, dynamic> _$MealItemToJson(MealItem instance) => <String, dynamic>{
'id': instance.id,
'ingredient': instance.ingredient,
'weightUnit': instance.weightUnit,
'amount': instance.amount,
};

View File

@@ -1,16 +1,30 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/nutrition/meal.dart';
part 'nutritional_plan.g.dart';
@JsonSerializable(explicitToJson: true)
class NutritionalPlan {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String description;
final DateTime date;
@JsonKey(required: true, name: 'creation_date')
final DateTime creationDate;
@JsonKey(required: false)
final List<Meal> meals;
NutritionalPlan({
@required this.id,
@required this.description,
@required this.date,
@required this.meals,
this.id,
this.description,
this.creationDate,
this.meals,
});
// Boilerplate
factory NutritionalPlan.fromJson(Map<String, dynamic> json) => _$NutritionalPlanFromJson(json);
Map<String, dynamic> toJson() => _$NutritionalPlanToJson(this);
}

View File

@@ -0,0 +1,30 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'nutritional_plan.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
NutritionalPlan _$NutritionalPlanFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const ['id', 'description', 'creation_date']);
return NutritionalPlan(
id: json['id'] as int,
description: json['description'] as String,
creationDate: json['creation_date'] == null
? null
: DateTime.parse(json['creation_date'] as String),
meals: (json['meals'] as List)
?.map(
(e) => e == null ? null : Meal.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$NutritionalPlanToJson(NutritionalPlan instance) =>
<String, dynamic>{
'id': instance.id,
'description': instance.description,
'creation_date': instance.creationDate?.toIso8601String(),
'meals': instance.meals?.map((e) => e?.toJson())?.toList(),
};

View File

@@ -1,11 +1,22 @@
import 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
part 'weight_unit.g.dart';
@JsonSerializable()
class WeightUnit {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String name;
WeightUnit({
@required this.id,
@required this.name,
});
// Boilerplate
factory WeightUnit.fromJson(Map<String, dynamic> json) => _$WeightUnitFromJson(json);
Map<String, dynamic> toJson() => _$WeightUnitToJson(this);
}

View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'weight_unit.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
WeightUnit _$WeightUnitFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const ['id', 'name']);
return WeightUnit(
id: json['id'] as int,
name: json['name'] as String,
);
}
Map<String, dynamic> _$WeightUnitToJson(WeightUnit instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
};

View File

@@ -0,0 +1,91 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/auth.dart';
class NutritionalPlans with ChangeNotifier {
static const nutritionPlansUrl = '/api/v2/nutritionplan/';
String _url;
Auth _auth;
List<NutritionalPlan> _entries = [];
NutritionalPlans(Auth auth, List<NutritionalPlan> entries) {
this._auth = auth;
this._entries = entries;
this._url = auth.serverUrl + nutritionPlansUrl;
}
List<NutritionalPlan> get items {
return [..._entries];
}
NutritionalPlan findById(int id) {
return _entries.firstWhere((plan) => plan.id == id);
}
Future<void> fetchAndSetPlans() async {
final response = await http.get(
_url,
headers: <String, String>{'Authorization': 'Token ${_auth.token}'},
);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<NutritionalPlan> loadedPlans = [];
if (loadedPlans == null) {
return;
}
try {
for (final entry in extractedData['results']) {
loadedPlans.add(NutritionalPlan.fromJson(entry));
}
_entries = loadedPlans;
notifyListeners();
} catch (error) {
throw (error);
}
}
Future<void> addPlan(NutritionalPlan plan) async {
try {
final response = await http.post(
_url,
headers: {
'Authorization': 'Token ${_auth.token}',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(plan.toJson()),
);
print(plan.toJson());
print(json.decode(response.body));
_entries.add(NutritionalPlan.fromJson(json.decode(response.body)));
notifyListeners();
} catch (error) {
print(error);
throw error;
}
}
Future<void> deletePlan(int id) async {
final url = '$_url$id/';
final existingPlanIndex = _entries.indexWhere((element) => element.id == id);
var existingPlan = _entries[existingPlanIndex];
_entries.removeAt(existingPlanIndex);
notifyListeners();
final response = await http.delete(
url,
headers: {'Authorization': 'Token ${_auth.token}'},
);
if (response.statusCode >= 400) {
_entries.insert(existingPlanIndex, existingPlan);
notifyListeners();
//throw HttpException();
}
existingPlan = null;
}
}

View File

@@ -45,11 +45,7 @@ class WorkoutPlans with ChangeNotifier {
try {
for (final entry in extractedData['results']) {
loadedWorkoutPlans.add(WorkoutPlan(
id: entry['id'],
description: entry['comment'],
creationDate: DateTime.parse(entry['creation_date']),
));
loadedWorkoutPlans.add(WorkoutPlan.fromJson(entry));
}
_entries = loadedWorkoutPlans;

View File

@@ -1,9 +1,18 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/nutritional_plans.dart';
import 'package:wger/providers/workout_plans.dart';
import 'package:wger/widgets/app_drawer.dart';
import 'package:wger/widgets/nutrition/nutritional_plans_list.dart';
class NutritionScreen extends StatelessWidget {
static const routeName = '/nutrition';
Future<void> _refreshPlans(BuildContext context) async {
await Provider.of<NutritionalPlans>(context, listen: false).fetchAndSetPlans();
}
Widget getAppBar() {
return AppBar(
title: Text('Nutrition'),
@@ -22,9 +31,24 @@ class NutritionScreen extends StatelessWidget {
appBar: getAppBar(),
drawer: AppDrawer(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
onPressed: () {
Provider.of<NutritionalPlans>(context, listen: false).addPlan(
NutritionalPlan(description: 'button'),
);
},
child: const Icon(Icons.add),
),
body: FutureBuilder(
future: _refreshPlans(context),
builder: (context, snapshot) => snapshot.connectionState == ConnectionState.waiting
? Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: () => _refreshPlans(context),
child: Consumer<WorkoutPlans>(
builder: (context, productsData, child) => NutritionalPlansList(),
),
),
),
);
}
}

View File

@@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:wger/providers/nutritional_plans.dart';
class NutritionalPlansList extends StatelessWidget {
@override
Widget build(BuildContext context) {
final nutritrionalPlansData = Provider.of<NutritionalPlans>(context);
return ListView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: nutritrionalPlansData.items.length,
itemBuilder: (context, index) {
final currentPlan = nutritrionalPlansData.items[index];
return Dismissible(
key: Key(currentPlan.id.toString()),
onDismissed: (direction) {
// Delete workout from DB
Provider.of<NutritionalPlans>(context, listen: false).deletePlan(currentPlan.id);
// and inform the user
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(
"Workout ${currentPlan.id} deleted",
textAlign: TextAlign.center,
),
),
);
},
background: Container(
color: Theme.of(context).errorColor,
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20),
margin: EdgeInsets.symmetric(
horizontal: 4,
vertical: 4,
),
child: Icon(
Icons.delete,
color: Colors.white,
),
),
direction: DismissDirection.endToStart,
child: Card(
child: ListTile(
//onTap: () => Navigator.of(context).pushNamed(
// WorkoutPlanScreen.routeName,
// arguments: currentPlan,
//),
onTap: () {},
title: Text(
DateFormat('dd.MM.yyyy').format(currentPlan.creationDate).toString(),
),
subtitle: Text(currentPlan.description),
),
),
);
},
);
}
}