Flutter:在单击按钮时动态添加/删除列表视图中的项目

时间:2019-05-31 07:48:13

标签: listview flutter

我是Flutter的新手。我的查询是如何在单击按钮时在列表视图中动态添加/删除项目。我尝试过但是我得到了

错误:RenderFlex子级的flex值非零,但传入的高度限制不受限制

我的代码

     Padding(
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
                child: SizedBox(
                  width: double.infinity,
                  height: 52,
                  child: RaisedButton(
                      //onPressed: () 
                     =>_onAlertWithCustomContentPressed(context),
                    onPressed:() =>call(),
                    child: Text(
                      "Add Article",
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                    color: Colors.green,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6))),
                  ),
                ),
              ),

           new Expanded(
    child: new ListView.builder
      (
        itemCount: lItems.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return new Text(lItems[Index]);
        }
    )
)

任何人都可以提供帮助。或者任何人都可以建议哪种方法最适合此任务

预先感谢

Sathish

4 个答案:

答案 0 :(得分:2)

我知道为时已晚,但也许其他人正在寻找相同的答案,以下代码可以帮助他们。

使用StatefullWidget,以便稍后可以更改状态,并使用setState((){}        //您的代码在这里

import 'package:flutter/material.dart';

class MyListView extends StatefulWidget {
@override
_MyListViewState createState() => _MyListViewState();
 }

class _MyListViewState extends State<MyListView> {
final countries = [
'Pakistan',
'France',
'Spain',
'KSA',
'Brasil',
'Australia',
'UAE',
'USA',
'UK',
'India',
'Afghanistan',
'Bangladsh',
'Egypt',
'Pakistan',
'France',
'Spain',
'KSA',
'Brasil',
'Australia',
'UAE',
'USA',
'UK',
'India',
'Afghanistan',
'Bangladsh',
'Egypt'
];

@override
Widget build(BuildContext context) {
return Scaffold(
  body: Padding(
    padding: const EdgeInsets.all(8.0),
    child: ListView.separated(
        itemCount: countries.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(countries[index]),
          );
        },

        separatorBuilder: (context, index){

          return Divider();
  },
        ),
  ),
  floatingActionButton: FloatingActionButton(
    child: Icon(Icons.add),
    onPressed: addItem,
  ),
  );
   }


void addItem(){

setState(() {
  countries.add(countries[0]);
});

}

}

答案 1 :(得分:2)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final List<String> names = <String>['Aby', 'Aish', 'Ayan', 'Ben', 'Bob', 'Charlie', 'Cook', 'Carline'];
  final List<int> msgCount = <int>[2, 0, 10, 6, 52, 4, 0, 2];

  TextEditingController nameController = TextEditingController();

  void addItemToList(){
    setState(() {
      names.insert(0,nameController.text);
      msgCount.insert(0, 0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tutorial - googleflutter.com'),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(20),
            child: TextField(
              controller: nameController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Contact Name',
              ),
            ),
          ),
          RaisedButton(
            child: Text('Add'),
            onPressed: () {
              addItemToList();
            },
          ),
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: names.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: 50,
                  margin: EdgeInsets.all(2),
                  color: msgCount[index]>=10? Colors.blue[400]:
                    msgCount[index]>3? Colors.blue[100]: Colors.grey,
                  child: Center(
                    child: Text('${names[index]} (${msgCount[index]})',
                      style: TextStyle(fontSize: 18),
                    )
                  ),
                );
              }
            )
          )
        ]
      )
    );
  }
}

答案 2 :(得分:0)

您可以使用此代码在列表视图中添加新元素

  List<String> listObj = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: <Widget>[
            new FlatButton(
              onPressed: _insertNewObj,
              child: new Icon(Icons.add),
            )
          ],
        ),
        body: Column(
          children: <Widget>[
            new InkWell(
              onTap: _insertNewObj,
              child: new Container(
                width: double.infinity,
                alignment: Alignment.center,
                color: Colors.blue,
                padding: const EdgeInsets.all(20.0),
                child: new Text('Add new'),
              ),
            ),
            new Expanded(
              child: new ListView.builder(
                  itemCount: listObj.length,
                  itemBuilder: (BuildContext context, int index) => new Text(
                      'index ${index.toString()} with value ${listObj[index].toLowerCase()}')),
            ),
          ],
        ));
  }

  void _insertNewObj() {
    var rng = new Random();
    setState(() {
      listObj.add(rng.nextInt(100).toString());
    });
  }

随机导入数学,否用于添加列表数组。

import 'dart:math';//for random no generation.

答案 3 :(得分:0)

如果Padding,Expanded是Column的子级,请尝试将mainaxissize设置为min

Column(
 mainAxisSize : min ;
 children: <Widget>[
  new Expanded(
    child: new ListView.builder
      (
        itemCount: lItems.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return new Text(lItems[Index]);
        }
    )
   )
  ]
)