Search code examples
flutterdartandroid-widget

Dynamic dropdownbuttons


Im working on a small project for which i need a lot of drop down buttons, so i decided to make it dynamic ,so i created a separate class for the dropdownbutton , but im getting an error when i run it, i dont know where the error is, is there any other efficient way of doing this?and where am i making the mistake

import "package:flutter/material.dart";
import "buttons.dart";

void main(){
  runApp(My_app());
}

class My_app extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _My_app();
  }
}

class _My_app extends State<My_app>{
  var color_list = ["RED","GREEN","BLUE"];
  var weight_list = ["300","400","800"];
  var color = [Colors.red,Colors.green,Colors.blue];
  var weight = [FontWeight.w300,FontWeight.w400,FontWeight.w800];
  var color_var = 0;
  var weight_var = 0;
  var milo = "RED" ;
  Widget build(BuildContext context){
    return MaterialApp(
      title:"Font Designer",
      home:Material(
        child:Center(
          child:Container(
            child:Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.only(top:40),
                      child:Dropy(color_list,color,color_var)
                    )
                  ]
                )
              ],
            )
          )
        )
      )
    );
  }

}

//buttons.dart

import "package:flutter/material.dart";

class Dropy extends StatefulWidget{

  var listy;
  var power;
  var varie;

  Dropy(var k,var m,var n){
    this.listy = k;
    this.power = m;
    this.varie = n;
  }

  State<StatefulWidget> createState(){
    return _Dropy(this.listy,this.power,this.varie);
  }
}

class _Dropy extends State<Dropy>{

  var tex;
  var liy;
  var pow;
  var va;
  var male;

  _Dropy(var o,var p,var z){
    this.liy = o;
    this.pow = p;
    this.va = z;
  }

  Widget build(BuildContext context){
    return DropdownButton<String>(
      items:liy.map((String etx) {
        return DropdownMenuItem<String>(
            value: etx,
            child: Text(etx)
        );
      }).toList(),
      onChanged: (String milo){
        setState(() {
          this.va = this.liy.indexOf(male);
          male = milo;
        });
      },
      value: male,);
  }
}

Solution

  • There are two package you can reference source code or directly use it
    You can use package https://pub.dev/packages/find_dropdown
    It also support search and validation

    full example code

    import 'package:dio/dio.dart';
    import 'package:flutter/material.dart';
    import 'package:find_dropdown/find_dropdown.dart';
    
    import 'user_model.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("FindDropdown Example")),
          body: Padding(
            padding: const EdgeInsets.all(25),
            child: Column(
              children: <Widget>[
                FindDropdown(
                  items: ["Brasil", "Itália", "Estados Unidos", "Canadá"],
                  label: "País",
                  onChanged: print,
                  selectedItem: "Brasil",
                  showSearchBox: false,
                  validate: (String item) {
                    if (item == null)
                      return "Required field";
                    else if (item == "Brasil")
                      return "Invalid item";
                    else
                      return null;
                  },
                ),
                FindDropdown<UserModel>(
                  label: "Nome",
                  onFind: (String filter) => getData(filter),
                  searchBoxDecoration: InputDecoration(
                    hintText: "Search",
                    border: OutlineInputBorder(),
                  ),
                  onChanged: (UserModel data) => print(data),
                ),
                FindDropdown<UserModel>(
                  label: "Personagem",
                  onFind: (String filter) => getData(filter),
                  onChanged: (UserModel data) {
                    print(data);
                  },
                  dropdownBuilder: (BuildContext context, UserModel item) {
                    return Container(
                      decoration: BoxDecoration(
                        border: Border.all(color: Theme.of(context).dividerColor),
                        borderRadius: BorderRadius.circular(5),
                        color: Colors.white,
                      ),
                      child: (item?.avatar == null)
                          ? ListTile(
                              leading: CircleAvatar(),
                              title: Text("No item selected"),
                            )
                          : ListTile(
                              leading: CircleAvatar(
                                backgroundImage: NetworkImage(item.avatar),
                              ),
                              title: Text(item.name),
                              subtitle: Text(item.createdAt.toString()),
                            ),
                    );
                  },
                  dropdownItemBuilder:
                      (BuildContext context, UserModel item, bool isSelected) {
                    return Container(
                      decoration: !isSelected
                          ? null
                          : BoxDecoration(
                              border:
                                  Border.all(color: Theme.of(context).primaryColor),
                              borderRadius: BorderRadius.circular(5),
                              color: Colors.white,
                            ),
                      child: ListTile(
                        selected: isSelected,
                        title: Text(item.name),
                        subtitle: Text(item.createdAt.toString()),
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(item.avatar),
                        ),
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        );
      }
    
      Future<List<UserModel>> getData(filter) async {
        var response = await Dio().get(
          "http://5d85ccfb1e61af001471bf60.mockapi.io/user",
          queryParameters: {"filter": filter},
        );
    
        var models = UserModel.fromJsonList(response.data);
        return models;
      }
    }
    

    enter image description here

    or use package https://pub.dev/packages/dropdown_formfield

    full example code of use

    import 'package:flutter/material.dart';
    import 'package:dropdown_formfield/dropdown_formfield.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String _myActivity;
      String _myActivityResult;
      final formKey = new GlobalKey<FormState>();
    
      @override
      void initState() {
        super.initState();
        _myActivity = '';
        _myActivityResult = '';
      }
    
      _saveForm() {
        var form = formKey.currentState;
        if (form.validate()) {
          form.save();
          setState(() {
            _myActivityResult = _myActivity;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Dropdown Formfield Example'),
          ),
          body: Center(
            child: Form(
              key: formKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(16),
                    child: DropDownFormField(
                      titleText: 'My workout',
                      hintText: 'Please choose one',
                      value: _myActivity,
                      onSaved: (value) {
                        setState(() {
                          _myActivity = value;
                        });
                      },
                      onChanged: (value) {
                        setState(() {
                          _myActivity = value;
                        });
                      },
                      dataSource: [
                        {
                          "display": "Running",
                          "value": "Running",
                        },
                        {
                          "display": "Climbing",
                          "value": "Climbing",
                        },
                        {
                          "display": "Walking",
                          "value": "Walking",
                        },
                        {
                          "display": "Swimming",
                          "value": "Swimming",
                        },
                        {
                          "display": "Soccer Practice",
                          "value": "Soccer Practice",
                        },
                        {
                          "display": "Baseball Practice",
                          "value": "Baseball Practice",
                        },
                        {
                          "display": "Football Practice",
                          "value": "Football Practice",
                        },
                      ],
                      textField: 'display',
                      valueField: 'value',
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(8),
                    child: RaisedButton(
                      child: Text('Save'),
                      onPressed: _saveForm,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(16),
                    child: Text(_myActivityResult),
                  )
                ],
              ),
            ),
          ),
        );
      }
    }
    

    enter image description here