首页 > 解决方案 > 颤动列表视图按钮以创建额外的孩子

问题描述

我正在处理的颤振应用程序中有一个列表视图,我希望能够根据按下按钮的时间向列表视图添加额外的项目。该按钮应位于所有项目下方。每次按下按钮时,我都想添加一个额外的容器。理想情况下,它将是一个小部件。我不知道该怎么做。这是我的代码:

body: ListView(
          children: <Widget>[
            Container(   //this is the container I would like to add another of when a button is pressed
              height: 200,
              child: optionsChoices(),
            ), //end container
            Container(
              height: 200,
              child: optionsChoices(),
            ),
            Container(
              height: 200,
              child: optionsChoices(),
            ),
            Container(
              height: 200,
              child: optionsChoices(),
            ),
          ]
        )

谢谢!

标签: flutterdartflutter-listview

解决方案


改为使用ListView.builder()包含容器小部件的列表以及setState()管理列表的状态。

import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int x = 60;
  List<Widget> a = [
      Container(
        height: 200,
        child: Text('Test'),
      )
    ];
  void _d() {
    setState(() {
      a.add(Container(
                    height: 200,
                    child: Text('Test'),
                  ));
    });
  }

  Widget build(context) {

    return Scaffold(
        appBar: AppBar(),
        body: Column(
          children: <Widget>[
            FlatButton(
                onPressed: () {
                  _d();

                },
                child: Text('Press here to add item')),
            Expanded(
              child: ListView.builder(
                  itemCount: a.length,
                  itemBuilder: (context, index) {
                    return a[index];
                  }),
            ),
          ],
        ));
  }
}

推荐阅读