Flllter在ListView Builder上设置默认ItemCount

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

我正在尝试使用ListView Builder构建一些输入字段,并将默认的构建字段设置为3,然后使用floatActionButtion添加到数字以生成更多字段。

但我设置的3个默认字段没有显示,我无法理解发生了什么。

这是我的代码。

int newSULength = 3;

new Expanded(
              child: new Form(
                key: formKey,
                child: new ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return buildfields(index);
                  },
                  itemCount: newSULength,
                  scrollDirection: Axis.vertical,
                ),
              ),
            )
floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {
            newSULength++;
          });
        },
        child: new Icon(Icons.add),
      )

下面是我正在尝试构建的字段。

    Widget buildfields(int index) {
    return new Container(
      margin: EdgeInsets.only(bottom: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          _deleteMode ? deleteButton(index) : null,
          Container(
            width: 110.0,
            child: TextFormField(
              onSaved: (String value) {
                setState(() {
                  _course = value;
                });
              },
              initialValue: 'GNS101',
              inputFormatters: [
                new LengthLimitingTextInputFormatter(6),
              ],
              validator: (val) {
                return val.isEmpty ? "Enter Course Code" : null;
              },
              textCapitalization: TextCapitalization.characters,
              decoration: new InputDecoration(
                border: UnderlineInputBorder(),
                contentPadding: EdgeInsets.fromLTRB(20.0, 5.0, 20.0, 8.0),
              ),
            ),
          ),
          new Container(
            child: new DropdownButton<num>(
              onChanged: (num value) {
                setState(() {
                  selectedGrade[index] = value;
                });
              },
              hint: new Text('Grade Point'),
              value: selectedGrade[index],
              items: <num>[0, 1, 2, 3, 4, 5].map((num value) {
                return new DropdownMenuItem<num>(
                  value: value,
                  child: new Text(value.toString()),
                );
              }).toList(),
            ),
          ),
          new Container(
            child: new DropdownButton<num>(
              onChanged: (num value) {
                setState(() {
                  selectedUnit[index] = value;
                });
              },
              hint: new Text('Course Unit'),
              value: selectedUnit[index],
              items: <num>[1, 2, 3, 4, 5].map((num value) {
                return new DropdownMenuItem<num>(
                  value: value,
                  child: new Text(value.toString()),
                );
              }).toList(),
            ),
          ),
        ].where(notNull).toList(),
      ),
    );
  }

更新:我发现我的问题是将selectedUnitselectedGrade声明为List。

List<num> selectedUnit = [];
List<num> selectedGrade = [];

我尝试使用selectedUnitselectedGrade作为地图,它的工作原理。

var selectedUnit = {};
var selectedGrade = {};

但我需要使用selectedUnit.contain()selectedUnit.add()检查列表是否包含某个值,这些在Map中不可用。

请帮忙。

dart flutter
1个回答
0
投票

以下应该适合你。我不确定确切的问题。我必须用你的代码填写一些内容来构建它。检查你的notNull逻辑,因为它可以返回一个空的List

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  int newSULength = 3;
  var selectedUnit = [0, 0, 0];
  var selectedGrade = [0, 0, 0];
  var _course = '';

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Form(
              key: _formKey,
              child: new ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return buildfields(index);
                },
                itemCount: newSULength,
                scrollDirection: Axis.vertical,
              ),
            ),
          )
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {
            newSULength++;
            selectedUnit.add(0);
            selectedGrade.add(0);
          });
        },
        child: new Icon(Icons.add),
      ),
    );
  }

  Widget buildfields(int index) {
    return new Container(
      margin: EdgeInsets.only(bottom: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 110.0,
            child: TextFormField(
              onSaved: (String value) {
                setState(() {
                  _course = value;
                });
              },
              initialValue: 'GNS101',
              inputFormatters: [
//                new LengthLimitingTextInputFormatter(6),
              ],
              validator: (val) {
                return val.isEmpty ? "Enter Course Code" : null;
              },
              textCapitalization: TextCapitalization.characters,
              decoration: new InputDecoration(
                border: UnderlineInputBorder(),
                contentPadding: EdgeInsets.fromLTRB(20.0, 5.0, 20.0, 8.0),
              ),
            ),
          ),
          new Container(
            child: new DropdownButton<num>(
              onChanged: (num value) {
                setState(() {
                  selectedGrade[index] = value;
                });
              },
              hint: new Text('Grade Point'),
              value: selectedGrade[index] != 0 ? selectedGrade[index] : null,
              items: <num>[0, 1, 2, 3, 4, 5].map((num value) {
                return new DropdownMenuItem<num>(
                  value: value,
                  child: new Text(value.toString()),
                );
              }).toList(),
            ),
          ),
          new Container(
            child: new DropdownButton<num>(
              onChanged: (num value) {
                setState(() {
                  selectedUnit[index] = value;
                });
              },
              hint: new Text('Course Unit'),
              value: selectedUnit[index] != 0 ? selectedUnit[index] : null,
              items: <num>[1, 2, 3, 4, 5].map((num value) {
                return new DropdownMenuItem<num>(
                  value: value,
                  child: new Text(value.toString()),
                );
              }).toList(),
            ),
          ),
        ].where((value) => value != null).toList(),
      ),
    );
  }
}

更新:如果您想继续使用Lists存储值,请使用占位符值初始化List成员变量。存储在List成员变量中的值的数量必须等于ListView中的元素数量。更新你的DropDownButtonvalue param以检查占位符并返回null(如果找到)。在您的FAB的onPressed中,请确保为新元素添加新的占位符值。 Maps或适当的模型都将是更好/未来的替代品。

© www.soinside.com 2019 - 2024. All rights reserved.