【问题标题】:ListView update doesn't update after new ListTile gets added as a children in Flutter在 Flutter 中将新的 ListTile 添加为子项后,ListView 更新不会更新
【发布时间】:2020-10-24 03:54:18
【问题描述】:

我有一个简单的颤动应用程序,它只显示一个 ListView 的 ListTiles...这个 listView 的子属性设置为一个名为“tiles”的列表...每当用户按下浮动操作按钮然后一个新的ListTiles 对象被添加到“tiles”中,并且它被包裹在 set 状态中......所以我希望 UI 能够更新并向我显示带有更多 ListTiles 的新更新的 listView......但事实并非如此发生...

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<ListTile> tiles = [];

  @override
  Widget build(BuildContext context) {
    print('length of tiles: ${tiles.length}');  // prints the length of tiles correctly
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            tiles.add(ListTile(title: Text('Hello ${tiles.length+1}')));
          });
        },
      ),
      body: ListView(children: tiles),
    );
  }
}

【问题讨论】:

  • 你真的想用ListView.builder来处理这些事情,并用字符串列表替换小部件列表

标签: flutter flutter-listview


【解决方案1】:

就像@LonelyWolf 所说:您应该使用ListView.builder 并将字符串添加到您的列表而不是小部件

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<String> tiles = [];

  @override
  Widget build(BuildContext context) {
    print('length of tiles: ${tiles.length}');  // prints the length of tiles correctly
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            tiles.add("${tiles.length+1}");
          });
        },
      ),
      body: ListView.builder(
        itemCount: tiles.length,
        itemBuilder: (_, index){
          return ListTile(
            title: Text('Hello ${tiles[index]}'),
          );
        },
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2020-11-16
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多