Flutter在ListView Builder上设置默认ItemCount

时间:2018-09-06 14:51:02

标签: dart flutter

我正在尝试使用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<num> selectedUnit = [];
List<num> selectedGrade = [];

我尝试使用selectedUnitselectedGrade作为地图,并且可以使用。

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

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

请帮助。

1 个答案:

答案 0 :(得分: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(),
      ),
    );
  }
}

更新:如果要继续使用List来存储值,请使用占位符值初始化List成员变量。 List成员变量中存储的值数必须等于ListView中的元素数。更新DropDownButton的{​​{1}}参数以检查占位符,如果找到则返回value。确保在FAB的null中,为新元素添加新的占位符值。 onPressed或适当的模型都将是更好/未来的选择。