Flutter - ListTile的循环

5

我不确定如何通过循环(例如for())生成多个ListTiles。

我不知道Flutter如何渲染小部件,因为在Angular 2中只需在布局(html)中插入*ngFor指令即可。

我在Flutter文档中找不到这样的主题。

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView (
      children: <Widget>[
        new Card(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const ListTile(
                leading: const Icon(Icons.album),
                title: const Text('The Enchanted Nightingale'),
                subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
              ),
            ],
          ),
        ),
      ],
    )    
  );
}
2个回答

10

List.generate() 函数适用于创建小型列表。对于较大或无限列表,请使用 ListView.builder() 而不是 ListView

screenshot

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor: new Color(0xFF26C6DA),
      ),
      body: new ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return new Card(
            child: const ListTile(
              leading: const Icon(Icons.album),
              title: const Text('The Enchanted Nightingale'),
              subtitle: const Text(
                'Music by Julie Gable. Lyrics by Sidney Stein.',
              ),
            ),
          );
        },
      ),
    );
  }
}

还要在ListView.builder下添加itemCount属性,以指定itemBuilder中元素的数量。 - Tox

3

下面是使用List.generate的示例:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('List.generate demo'),
      ),
      body: new ListView(
        padding: const EdgeInsets.all(8),
        children: new List.generate(
          10,
          (index) => new ListTile(
            title: Text('Item $index'),
          ),
        ),
      ),
    );
  }
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接