每当项目位于顶部时,列表视图中的项目都会刷新

时间:2019-01-11 15:12:43

标签: flutter

我有一个ListView包含ListItem实例,它们都是有状态的小部件。每当我按下floatingActionButton时,都会在列表顶部插入一个新的ListItem

插入正常,但其他项将刷新(称为initState)。

这是我的main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter ListView test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<ListItem> _list = [
    ListItem(key: UniqueKey()),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: _list.toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          print('button onPressed');
          setState(() {
            _list.insert(
              0,
              ListItem(key: UniqueKey()),
            );
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class ListItem extends StatefulWidget {
  ListItem({Key key}) : super(key: key);

  @override
  _ListItemState createState() => _ListItemState();
}

class _ListItemState extends State<ListItem> {
  @override
  void initState() {
    super.initState();
    print('ListItem initState: ${widget.key.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      '${widget.key.toString()}',
      style: TextStyle(fontSize: 30),
    );
  }
}

以下是示例输出日志:

I/flutter (10880): ListItem initState: [#47a4d]
I/flutter (10880): button onPressed
I/flutter (10880): ListItem initState: [#21660]
I/flutter (10880): ListItem initState: [#47a4d]
I/flutter (10880): button onPressed
I/flutter (10880): ListItem initState: [#01755]
I/flutter (10880): ListItem initState: [#21660]
I/flutter (10880): ListItem initState: [#47a4d]
I/flutter (10880): button onPressed
I/flutter (10880): ListItem initState: [#7b24f]
I/flutter (10880): ListItem initState: [#01755]
I/flutter (10880): ListItem initState: [#21660]
I/flutter (10880): ListItem initState: [#47a4d]

如果我将项目附加到列表末尾(由_list.add附加,则其他项目将不会刷新。

我想项目也不应该用_list.insert刷新,因为每个ListItem都有一个key。我错了吗?或误解了什么?

0 个答案:

没有答案