Флаттер выпадающая пара ключ-значение - PullRequest
0 голосов
/ 01 февраля 2020

Хотя у меня многолетний опыт программирования, я новичок в разработке Flutter. Кажется, я застрял в основной проблеме c, и мне еще не удалось найти правильные условия поиска, чтобы получить правильный результат. Я подхожу близко, но, похоже, ничто не соответствует моему конкретному c сценарию использования.

        //SupplyType model
        class SupplyType {
        int _id;
        String _supplyTypeName;

        //...(constructors, getters, setters, maps)
        }

        //Quantity Type model
        class QuantityType {
        int _id;
        String _quantityTypeName;

        //...(constructors, getters, setters, maps)
        }

        //Supply model
        class SupplyRequirement {
        int _id;
        int _supplyTypeId;
        double _quantity;
        int _quantityTypeId;
        String _description;
        //...
        String _supplyTypeName;  //added here so that the model 'understands' this,
                                //but I don't think this is correct
        String _quantityTypeName;  //ditto from above

        //...(constructors, getters, setters)

        Map<String, dynamic> toMap() {
        var map = Map<String, dynamic>();
        if (id != null) {
          map['id'] = _id;
        }

        //...map of fields
        return map;
        }  //SupplyTypeName and QuantityTypeName NOT in here so that insert works

        SupplyRequirement.fromMapObject(Map<String, dynamic> map) {
        this._id = map['id'];
        //...map of fields
        this._supplyTypeName = map['$kColSupplyTypeName'];
        this._quantityTypeName = map['$kColQuantTypeName'];
        }  //SupplyTypeName and QuantityTypeName here so select from works
        }

        //databaase helper class  - this works...
        Future<List<Map<String, dynamic>>> getSupplyReqLookupMap(
          String tableName) async {
        Database db = await this.db;
        String sql =
            '''SELECT a.id a.$kColSupplyTypeId, a.$kColQuantity, a.$kColQuantityTypeId
            , a.$kColDescription, b.$kColSupplyTypeName, c.$kColQuantTypeName //lookup names here
          FROM $kTabSupplyRequirement a 
          INNER JOIN $kTabSupplyType b ON a.$kColSupplyTypeId = b.id 
          INNER JOIN $kTabQuantType c on a.$kColQuantityTypeId = c.id''';
        var result = await db.rawQuery(sql);
        return result;
        }

Все вышеперечисленное работает для создания моей страницы списка (методом проб и ошибок), но я подозреваю, что я не реализовал ее правильно. Вот страница с сокращенным списком:

        class SupplyReqList extends StatefulWidget {

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

        class _SupplyReqListState extends State<SupplyReqList> {

          DatabaseHelper dbHelper = DatabaseHelper();
          List<SupplyRequirement> supplyRequirementList;
          int count = 0;

          @override
          Widget build(BuildContext context) {
            if (supplyRequirementList == null) {
              supplyRequirementList = List<SupplyRequirement>();
              updateListView();
            }

            return Scaffold(
              appBar: AppBar(
                title: Text('Supply Requirements'),
                leading: GestureDetector(
                  child: Icon(Icons.arrow_back),
                  onTap: () {
                    Navigator.pop(context, true);
                  },
                ),
              ),
              body: Padding(
                padding: const EdgeInsets.all(8.0),
                child: getListView(),
              ),
            );
          }

          ListView getListView() {
            return ListView.builder(
              itemCount: count,
              itemBuilder: (BuildContext context, int position) {
                return Card(
                  color: Colors.white,
                  elevation: 2.0,
                  child: ListTile(
                    title: Text(
                      this.supplyRequirementList[position].supplyTypeName,
                    ),
                    subtitle: Text(
                        this.supplyRequirementList[position].quantity.toString() +
                            ' ' +
                            this.supplyRequirementList[position].quantityTypeName +
                            ' ' +
                            this.supplyRequirementList[position].description),
                    trailing: GestureDetector(
                      child: Icon(
                        Icons.delete,
                        color: Color(0xFF673AB7),
                      ),
                      onTap: () {
                        _delete(context, supplyRequirementList[position]);
                      },
                    ),
                    onTap: () {
                      navigateToDetail(this.supplyRequirementList[position],
                          'Edit Supply Requirement');
                    },
                  ),
                );
              },
            );
          }
        }

Но я не могу получить свой выпадающий список на следующей («подробной») странице, чтобы поиграть со справочной таблицей, в частности, я не знаю, как передать сохраненное значение из SupplyRequirement в выбранное значение из выпадающего списка:

         class SupplyReqDetail extends StatefulWidget {
          final String appBarTitle;
          final SupplyRequirement supplyRequirement;

          SupplyReqDetail(this.supplyRequirement, this.appBarTitle);

          @override
          _SupplyReqDetailState createState() =>
              _SupplyReqDetailState(supplyRequirement, appBarTitle);
        }

        class _SupplyReqDetailState extends State<SupplyReqDetail> {
          _SupplyReqDetailState(this.supplyRequirement, this.appBarTitle);

          List<SupplyType> supplyTypes = List<SupplyType>();
          SupplyType selectedSupplyType;

          @override
          initState() {
            super.initState();
            _loadSupplyTypes();
          }

          DatabaseHelper dbHelper = DatabaseHelper();

          String appBarTitle;
          SupplyRequirement supplyRequirement;

          @override
          Widget build(BuildContext context) {
            //selectedSupplyType = supplyRequirement.supplyTypeName;  ?????????

            return Scaffold(
              appBar: AppBar(
                title: Text(appBarTitle),
              ),
              body: Padding(
                padding: const EdgeInsets.all(16.0),
                child: ListView(
                  children: <Widget>[
                    DropdownButtonFormField<SupplyType>(
                      value: selectedSupplyType,
                      decoration: InputDecoration(
                        labelText: 'Supply Type',
                        labelStyle: Theme.of(context).textTheme.body1,
                        hintText: 'Enter the supply type',
                      ),
                      onChanged: (SupplyType newValue) {
                        setState(() {
                          selectedSupplyType = newValue;
                        });
                      },
                      items: supplyTypes.map((SupplyType supplyType) {
                        return new DropdownMenuItem<SupplyType>(
                          value: supplyType,
                          child: new Text(
                            supplyType.supplyTypeName,
                            style: Theme.of(context).textTheme.body1,
                          ),
                        );
                      }).toList(),
                    ),
                  ],
                ),
              ),
            );
          }

          _loadSupplyTypes() async {
            final Future<Database> dbFuture = dbHelper.initializeDB();
            SupplyTypeDao supplyTypeDao = SupplyTypeDao();
            dbFuture.then((database) {
              Future<List<SupplyType>> supplyTypeListFuture =
                  supplyTypeDao.getSupplyTypeListWithSort();
              supplyTypeListFuture.then((supplyTypeList) {
                setState(() {
                  this.supplyTypes = supplyTypeList;
                });
              });
            });
          }
        }

...