动态将项目追加到ListView [英] Append items dynamically to ListView

查看:84
本文介绍了动态将项目追加到ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Dart和Flutter的新手,并尝试将新项目追加到我的ListView.我创建了一个递增this.value的按钮,但没有任何反应.我是否错过了UI上的更新调用,这甚至是正确的方法吗? 由于我将ListView.builder的值直接返回给build的调用者,因此我不确定如何获取列表以添加更多项.非常感谢!

I am new to Dart and Flutter and try to append a new item to my ListView. I created a button that increments this.value but nothing happens. Am I missing an update call on the UI and is this even the correct approach? Since I return the value of ListView.builder directly to the caller of build I am not sure how to get the list to add more items. Thanks a lot!

class MyList extends State<MyList> {

... 
int value = 2;

@override
Widget build(BuildContext context) {
return ListView.builder(
    itemCount: this.value,
    itemBuilder: (context, index) => this._buildRow(index)
);

TL; DR:是调用setState触发UI更新的正确方法吗?

TL;DR: Is calling setState the correct way to trigger an UI update?

推荐答案

调用setState是触发UI更新的正确方法.

Calling setState is the correct way of triggering an UI update.

文档:

调用setState通知框架 该对象的更改方式可能会影响用户界面 在此子树中,这导致框架为 这个State对象.

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

如果您仅直接更改状态而不调用setState,则 框架可能不会安排构建,为此用户界面 子树可能不会更新以反映新状态.

If you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.

这是ListView的一个小示例,其中Button会向其附加项目.

Here is a small example of a ListView with a Button that appends items to it.

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(home: MyList()));

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  int value = 2;

  _addItem() {
    setState(() {
      value = value + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("MyApp"),
      ),
      body: ListView.builder(
          itemCount: this.value,
          itemBuilder: (context, index) => this._buildRow(index)),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem,
        child: Icon(Icons.add),
      ),
    );
  }

  _buildRow(int index) {
    return Text("Item " + index.toString());
  }
}

这篇关于动态将项目追加到ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆