简体   繁体   中英

I have an issue saving a different list on multiple dropdown button in Flutter

I'm a rookie in Flutter, and programming after all. I'm working on my final project for graduate as civil engineer, but I decided to program an app for Android that calculates various equations for design of micropiles.

I've completed code that simulates a pizza order (this is becoming more friendly the explication), but I have an issue saving values from different lists that change depending of the pizza vegan or meat, I am still working on that.

I can reach the method or form for do that, please, someone give a explain or help me for that.

The code so far:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

//Provider
class Datos with ChangeNotifier {
  List _datos = [' '];

  List get datos => _datos;

  set datos(List value){
    _datos = value;
    notifyListeners();
  }

  void goVegan () {
    _datos = [' ','Vegan 1', 'Vegan 2', 'Vegan 3'];
    notifyListeners();
  }

  void goMeat () {
    _datos = [' ', 'Meat 1', 'Meat 2', 'Meat 3'];
    notifyListeners();
  }
}

class lechada extends StatelessWidget {
  // const lechada({Key? key}) : super(key: key);
  int nes = 0;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Datos>(
      create: (context) => Datos(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('definitivo'),
        ),
        body:Column(
          children: [
            entrada('cantidad de Pizzas'),
            cuerpo(),//nes),
          ],
        ),
      ),
    );
  }
  //inputs de formatos
  entrada(String hint){
    return TextFormField(
      validator: (String? value) { //Esta valida que no este vacio
        if (value == null || value.isEmpty) {
          return 'Campo requerido'; //campo en caso de que este vacio
        }
        return null;
      },
      onSaved: (value) => nes = int.parse(value!),//eje.add(double.parse(value!)), //Aca guarda el valor
      decoration: InputDecoration(
        hintText: hint,
        // icon: Icon(Icons.calendar_view_day_sharp, color: Color(0xFFB14246))
      ),
      keyboardType: TextInputType.number,
    );
  }
}

class cuerpo extends StatefulWidget {
  // const cuerpo({Key? key}) : super(key: key);
  int nes = 3;
  // cuerpo (int nes);
  @override
  State<cuerpo> createState() => _cuerpoState();
}

class _cuerpoState extends State<cuerpo> {
  // List selec = [' ','Pizza Vegan','Pizza Meat'];

  String initial = ' ';
  String initial2 = ' ';

  @override
  Widget build(BuildContext context) {
    final datos = Provider.of<Datos>(context,listen: false);
    return Column(
      children: [
        ListView.builder(
            shrinkWrap: true,
            itemCount: widget.nes ,
            itemBuilder: (BuildContext context, int index) => datosPizza(),
            // {
            //   return datosPizza();
            // },
            ),
        SizedBox(height: 20),
        Container(
          padding: EdgeInsets.all(8),
          child: Text('selec.toString()'),
        ),
        SizedBox(height: 20),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(onPressed: (){
              setState(() {
                initial = ' ';
                datos.goVegan();
              });
              }, child: Text('Go Vegan')),
            ElevatedButton(onPressed: (){
              setState(() {
                initial = ' ';
                datos.goMeat();
              });
            }, child: Text('Go Meat')),
          ],
        )
      ],
    );
  }
}

class datosPizza extends StatefulWidget {
  // const datosPizza({Key? key}) : super(key: key);

  @override
  _datosPizzaState createState() => _datosPizzaState();
}

class _datosPizzaState extends State<datosPizza> {
  List selec = [' ','Pizza Vegan','Pizza Meat'];

  String initial = ' ';
  String initial2 = ' ';

  @override
  Widget build(BuildContext context) {
    final datos = Provider.of<Datos>(context,listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Container(
          padding: EdgeInsets.all(8),
          child: DropdownButton(
              value: initial,
              //Aca recibe los valores y los pasa al map
              items: selec.map((value){ //datos se mete al list
                return DropdownMenuItem(
                  child: new Text(value),
                  value:value,
                );
              }).toList(),
              onChanged: (value) {
                value.toString() == 'Pizza Vegan' ?datos.goVegan() :null;
                value.toString() == 'Pizza Meat' ?datos.goMeat() :null;
                initial2 = ' ';
                setState(() {
                  initial = value.toString();
                });
              })
        ),
        Container(
          padding: EdgeInsets.all(8),
          child: DropdownButton(
              value: initial2,
              //Aca recibe los valores y los pasa al map
              items: datos.datos.map((value){ //datos se mete al list
                return DropdownMenuItem(
                  child: new Text(value),
                  value:value,
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  initial2 = value.toString();
                });
              })
        ),
      ],
    );
  }
}

Please, don't blame my English, I'm Hispanic native speaker

UPDATE: I have found a solution for the problem, simplifying is create more childrens for the principal tree widget, and inherit those values, so the widget will save these value that we need, i'll share the code sample:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

//Provider
class Datos with ChangeNotifier {
  List _datos = [' '];
  List guardado = [];
  List gg = [];
  List<String> esgua = [];
  List<double> algua = [];
  List<double> zgua = [];
  // List guardado = [' '];
  int p = 0;

  List get datos => _datos;

  set datos(List value){
    _datos = value;
    notifyListeners();
  }

  void goVegan () {
    _datos = [' ','Vegan 1', 'Vegan 2', 'Vegan 3'];
    // p = 0;
    notifyListeners();
  }

  void goMeat () {
    _datos = [' ', 'Meat 1', 'Meat 2', 'Meat 3'];
    // p = 1;
    notifyListeners();
  }

  void plus () {
    p++;
    notifyListeners();
  }

}

class lechada extends StatelessWidget {
  // const lechada({Key? key}) : super(key: key);
  // int nes = 0;


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Datos>(
      create: (context) => Datos(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('definitivo'),
        ),
        body:Column(
          children: [
            Text('Toma pedido'),
            cuerpo(),
          ],
        ),
      ),
    );
  }
}

class cuerpo extends StatefulWidget {
  // const cuerpo({Key? key}) : super(key: key);

  @override
  State<cuerpo> createState() => _cuerpoState();
}

class _cuerpoState extends State<cuerpo> {
  // List selec = [' ','Pizza Vegan','Pizza Meat'];

  String initial = ' ';
  String initial2 = ' ';
  // GlobalKey<FormState> dkey = GlobalKey<FormState>();


  @override
  Widget build(BuildContext context) {
    final datos = Provider.of<Datos>(context);
    return Column(
      children: [
        ListView.builder(
            shrinkWrap: true,
            itemCount: datos.p,
            itemBuilder: (BuildContext context, int index) => datosPizza(),
            // {
            //   return datosPizza();
            // },
            ),
        SizedBox(height: 20),
        Container(
          padding: EdgeInsets.all(8),
          child: Text('selec.toString()'),
        ),
        SizedBox(height: 20),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(
                onPressed: (){
                  setState(() {
                    print (datos.gg);
                    datos.p!=datos.gg.length
                        ?print ('error')
                        :null;
              });
              }, child: Text('Print')
            ),
            ElevatedButton(
                onPressed: (){
                  datos.p = 0;
                  datos.gg.clear();
                },
                child: Text('Reinicia')),
            ElevatedButton(
                onPressed: (){
                  datos.plus();
                },
                child: Text('Add estrato')
            ),
          ],
        )
      ],
    );
  }
}

class datosPizza extends StatefulWidget {
  const datosPizza({Key? key}) : super(key: key);

  @override
  _datosPizzaState createState() => _datosPizzaState();
}

class _datosPizzaState extends State<datosPizza> {
  List selec = [' ','Pizza Vegan','Pizza Meat'];

  String initial = ' ';
  String initial2 = ' ';
  List temp = [];
  List<double> eje = [];
  

  @override
  Widget build(BuildContext context) {
    final datos = Provider.of<Datos>(context,listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Container(
          width: 150,
          padding: EdgeInsets.all(8),
          child: DropdownButton(
              value: initial,
              //Aca recibe los valores y los pasa al map
              items: selec.map((value){ //datos se mete al list
                return DropdownMenuItem(
                  child: new Text(value),
                  value:value,
                );
              }).toList(),

              onChanged: (value) {
                value.toString() == 'Pizza Vegan' ?datos.goVegan() :null;
                value.toString() == 'Pizza Meat' ?datos.goMeat() :null;
                initial2 = ' ';
                temp.addAll(datos._datos); //Añade los datos de entrada y los pasa al widget para que los conserve
                setState(() {
                  initial = value.toString();
                });
              })
        ),
        Container(
          width: 100,
          padding: EdgeInsets.all(8),
          child: dropdowBut(temp),
        ),
        Container(
          width: 70,
          padding: EdgeInsets.all(8),
          child: entrada('mts'),
        )
      ],
    );
  }
  //inputs de formatos
  entrada(String hint){
    return TextFormField(
      validator: (String? value) { //Esta valida que no este vacio
        if (value == null || value.isEmpty) {
          return 'Campo requerido'; //campo en caso de que este vacio
        }
        return null;
      },
      onSaved: (value) => eje.add(double.parse(value!)),//eje.add(double.parse(value!)), //Aca guarda el valor
      onFieldSubmitted: (value) => print(value),
      // onChanged: (value)=> print(value),
      decoration: InputDecoration(
        hintText: hint,
        // icon: Icon(Icons.calendar_view_day_sharp, color: Color(0xFFB14246))
      ),
      keyboardType: TextInputType.number,
    );
  }
}

class dropdowBut extends StatefulWidget {
  // const dropdowBut({Key? key}) : super(key: key);
  String initial2 =' ';
  List temp ;


  dropdowBut(this.temp);


  @override
  _dropdowButState createState() => _dropdowButState();
}

class _dropdowButState extends State<dropdowBut> {
  String _value = ' ';

  @override
  Widget build(BuildContext context) {
    final datos = Provider.of<Datos>(context,listen: false);
    return DropdownButton(
        // value: widget.initial2,
        value: _value,
        // hint: Text('hi'),
        //Aca recibe los valores y los pasa al map
        items:
        widget.temp.map((value){ //datos se mete al list
          return DropdownMenuItem(
            child: new Text(value),
            value:value,
          );
        }).toList(),
        onChanged: (value) {
          datos.gg.add(value);
          setState(() {
            _value = value.toString();
          });
        });
  }
}

Sorry if i tangled the code, but i still learning Flutter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM