根据 android 中的用户选项对数据进行分类并存储在 firebase 中

问题描述 投票:0回答:0

下面的代码为用户提供了一个单选按钮来选择添加的食谱的类别。之后,它会自动将食谱分类并存储在 firebase_cloub 中。我尝试使用 if-else 语句,但不知道如何在选择单选选项后将它们插入其他页面。如何才能做到这一点? 这是 addRecipe.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:recipe_collector/All%20Recipes/viewpage.dart';

import '../Data/Model/recipeModel.dart';

//File? image; //https://stackoverflow.com/questions/67610330/the-name-file-is-defined-in-the-libraries-darthtml-and-dartio
String? filename;

class RecipeAddPage extends StatefulWidget {
  RecipeAddPage({super.key});

  @override
  State<RecipeAddPage> createState() => _RecipeAddPageState();
}

class _RecipeAddPageState extends State<RecipeAddPage> {
  
  final db = Firestore.instance;
  final _formKey = GlobalKey<FormState>();


  RecipeModel recipemodel = new RecipeModel();

  Future pickImageC() async {
    try {
      final image = await ImagePicker().getImage(source: ImageSource.camera);

      if (image == null) return;

      final imageTemp = File(image.path);

      setState(() => recipemodel.image = imageTemp);
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future pickImageG() async {
    try {
      final image = await ImagePicker().getImage(source: ImageSource.gallery);

      if (image == null) return;

      final imageTemp = File(image.path);

      setState(() => recipemodel.image = imageTemp);
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Widget divider() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
      child: Container(
        width: 0.8,
        color: Colors.black,
      ),
    );
  }

  // To store the information in the firebase - need time
  // Integrate with the firebase
  // implement later
  void createData() async {
    DateTime now = DateTime.now();
    String nuevoformato = DateFormat('kk:mm:ss:MMMMd').format(now);
    var fullImageName = 'nomfoto-$nuevoformato' + '.jpg';
    var fullImageName2 = 'nomfoto-$nuevoformato' + '.jpg';

    final StorageReference ref =
        FirebaseStorage.instance.ref().child(fullImageName);
    final StorageUploadTask task = ref.putFile(recipemodel.image);

    var part1 =
        'https://firebasestorage.googleapis.com/v0/b/recipe-collector-fd10f.appspot.com/o/';

    var fullPathImage = part1 + fullImageName2;
    print(fullPathImage);

    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      DocumentReference ref = await db.collection('colrecipes').add({
        'recipeName': '${recipemodel.recipeName}',
        'recipeDesc': '${recipemodel.recipeDesc}',
        'recipeTimePrepared': '${recipemodel.recipeTimePrepared}',
        'recipeServe': '${recipemodel.recipeServe}',
        'recipeIngredient': '${recipemodel.recipeIngredient}',
        'recipeStep': '${recipemodel.recipeStep}',
        'recipeNote': '${recipemodel.recipeNote}',
        'image': '$fullPathImage',
        'categoriesOption': '${recipemodel.categoriesOption}'
      });

      setState(() => recipemodel.rID = ref.documentID);
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    CommonThings.size = MediaQuery.of(context).size;

    return Scaffold(
        appBar: AppBar(
          title: Text('Add Recipe'),
        ),
        body: ListView(
          padding: EdgeInsets.all(8),
          children: <Widget>[
            Form(
                key: _formKey,
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        new Container(
                            height: 200.0,
                            width: 200.0,
                            decoration: new BoxDecoration(
                              border: new Border.all(color: Colors.blueAccent),
                            ),
                            padding: EdgeInsets.all(5.0),
                            child: recipemodel.image == null
                                ? Text("No image selected")
                                : new Image.file(recipemodel.image!)),
                        Divider(),
                        IconButton(
                            icon: const Icon(Icons.camera_alt),
                            onPressed: () {
                              pickImageC();
                            }),
                        Divider(),
                        IconButton(
                            icon: const Icon(Icons.image),
                            onPressed: () {
                              pickImageG();
                            }),
                      ],
                    ),
                    Container(
                      child: TextFormField(
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Recipe Name...',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Recipe Name...';
                          }
                        },
                        onSaved: (value) => recipemodel.recipeName = value!,
                      ),
                    ),
                    Container(
                      child: TextFormField(
                        maxLines: 5,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Recipes Description...',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Recipes Description...';
                          }
                        },
                        onSaved: (value) => recipemodel.recipeDesc = value!,
                      ),
                    ),
                    //                              //
                    // Insert the recipe categories //
                    //                              //
                    Column(
                      children: [
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              // title: const Text('Breakfast Recipes'),
                              value: "Breakfast",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Breakfast Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              //title: const Text('Baking Recipes'),
                              value: "Baking",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Baking Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              // title: const Text('Lunch Recipes'),
                              value: "Lunch",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Lunch Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              //title: const Text('Dinner Recipes'),
                              value: "Dinner",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Dinner Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              // title: const Text('Snack Recipes'),
                              value: "Snack",
                              onChanged: // handlesCategoriesChange
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Snack Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              //title: const Text('Dessert Recipes'),
                              value: "Dessert",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Dessert Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              //title: const Text('Cookies Recipes'),
                              value: "Cookies",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Cookies Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              //title: const Text('Vegeterian Recipes'),
                              value: "Vegeterian",
                              onChanged: //handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption =
                                      value!.toString();
                                });
                              },
                            ),
                            Text('Vegeterian Recipes'),
                          ],
                        ),
                        Row(
                          children: [
                            Radio<String>(
                              groupValue: recipemodel.categoriesOption,
                              // title: const Text('Soup Recipes'),
                              value: "Soup",
                              onChanged: //_handlesCategoriesChange,
                                  (String? value) {
                                setState(() {
                                  recipemodel.categoriesOption = value!;
                                });
                              },
                            ),
                            Text('Soup Recipes'),
                          ],
                        ),
                      ],
                    ),

                    Container(
                      child: TextFormField(
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Eg: 60m/120m/180m/240m',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Eg: 60m/120m/180m/240m';
                          }
                        },
                        onSaved: (value) =>
                            recipemodel.recipeTimePrepared = value!,
                      ),
                    ),
                    Container(
                      child: TextFormField(
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Eg: 2 peoples ',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Eg: 2 peoples';
                          }
                        },
                        onSaved: (value) => recipemodel.recipeServe = value!,
                      ),
                    ),
                    Container(
                      child: TextFormField(
                        maxLines: 10,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'List of ingredients... ',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'List of ingredients... ';
                          }
                        },
                        onSaved: (value) =>
                            recipemodel.recipeIngredient = value!,
                      ),
                    ),
                    Container(
                      child: TextFormField(
                        maxLines: 10,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Step description...',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Step description...';
                          }
                        },
                        onSaved: (value) => recipemodel.recipeStep = value!,
                      ),
                    ),
                    Container(
                      child: TextFormField(
                        maxLines: 10,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: 'Notes description...',
                          fillColor: Colors.grey[300],
                          filled: true,
                        ),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return 'Notes description...';
                          }
                        },
                        onSaved: (value) => recipemodel.recipeNote = value!,
                      ),
                    )
                  ],
                )),
            Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  ElevatedButton(
                    onPressed: createData,
                    child: Text('Save', style: TextStyle(color: Colors.white)),
                  ),
                ])
          ],
        ));
  }
}

这是 recipeModel.dart

import 'dart:core';
import 'dart:io';
import 'package:uuid/uuid.dart';

enum recipeCategories {
  breakfastRecipes,
  lunchRecipes,
  dinnerRecipes,
  snackRecipes,
  dessertRecipes,
  cookiesRecipes,
  bakingRecipes,
  vegeterianRecipes,
  soupRecipes,
}

class RecipeModel {
  String recipeName = '';
  late String recipeDesc;
  late String recipeTimePrepared;
  late String recipeServe;
  late String recipeIngredient;
  late String recipeStep;
  late String recipeNote;
  String? categoriesOption;
  File? image;
  String? rID;

  RecipeModel() {
    rID = Uuid().v1();
  }

//recipeName
  void set addRecipeName(String recipeName) {
    this.recipeName = recipeName;
  }

  String? get putRecipeName {
    return recipeName;
  }

//recipeDesc
  void set addRecipeDesc(String recipeDesc) {
    this.recipeDesc = recipeDesc;
  }

  String get putRecipeDesc {
    return recipeDesc;
  }

//recipeTimePrepared
  void set addRecipeTimePrepared(String recipeTimePrepared) {
    this.recipeTimePrepared = recipeTimePrepared;
  }

  String get putRecipeTimePrepared {
    return recipeTimePrepared;
  }

//recipeServe
  void set addRecipeServe(String recipeServe) {
    this.recipeServe = recipeServe;
  }

  String get putRecipeServe {
    return recipeServe;
  }

  //recipeIngredient;
  void set addRecipeIngredient(String recipeIngredient) {
    this.recipeIngredient = recipeIngredient;
  }

  String get addRecipeIngredient {
    return recipeIngredient;
  }

  // recipeStep;
  void set addRecipeStep(String recipeStep) {
    this.recipeStep = recipeStep;
  }

  String get addRecipeStep {
    return recipeStep;
  }

  //recipeNote;
  void set addRecipeNote(String recipeNote) {
    this.recipeNote = recipeNote;
  }

  String get addRecipeNote {
    return recipeNote;
  }

  //categoriesOption;
  void set addCategories(String categoriesOption) {
    this.categoriesOption = categoriesOption;
  }

  String? get putCategories {
    return categoriesOption;
  }

//File image
  void set addRecipeImage(File image) {
    this.image = image;
  }

  File? get putRecipeImage {
    return image;
  }

  //recipeIDs
  void set addRecipeIDs(String rID) {
    this.rID = rID;
  }

  String? get putRecipeIDs {
    return rID;
  }
}

flutter dart categories
© www.soinside.com 2019 - 2024. All rights reserved.