如何维护ListView中小部件的状态?

时间:2019-04-16 02:37:48

标签: listview flutter state

单击窗口小部件时,我有一个可单击的窗口小部件列表(即MarkWidget)。但是,当列表滚动到底部并滚动回到顶部时,所有小部件的状态都将重置为默认状态。

如何在滚动后停止/强制抖动以不重新绘制列表中的现有小部件?

例如: 如果我单击ITEM 1,则颜色从绿色变为红色,但是如果滚动到底部并向后滚动到顶部,则ITEM 1颜色将变为绿色。 如果不管滚动如何单击,我都需要将ITEM 1颜色设为红色。

DEMO

这是代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
      theme: ThemeData(
        platform: TargetPlatform.android,
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<Widget> _widgetList = List.generate(
    30,
    (index) => MarkWidget(
          key: Key('ITEM $index'),
          title: 'ITEM $index',
        ),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My List"),
      ),
      body: ListView.builder(
        key: new Key("my_list"), //new

        itemBuilder: (BuildContext context, int index) {
          return _widgetList[index];
        },
        itemCount: _widgetList.length,
      ),
    );
  }
}

class MarkWidget extends StatefulWidget {
  final String title;

  const MarkWidget({Key key, this.title}) : super(key: key);

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

class _MarkWidgetState extends State<MarkWidget> {
  bool _checked = false;

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      onPressed: () {
        setState(() {
          _checked = !_checked;
        });
      },
      child: Container(
        padding: EdgeInsets.all(10.0),
        margin: EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(5.0),
          ),
          color: _checked ? Colors.red : Colors.green,
        ),
        child: Text(
          "${widget.title}",
          style: TextStyle(
            color: Colors.white,
            decoration: _checked ? TextDecoration.lineThrough : TextDecoration.none,
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:3)

AutomaticKeepAliveClientMixin混合添加到State(项目小部件)的StatefulWidget中,覆盖wantKeepAlive方法并返回true

 class _MarkWidgetState extends State<MarkWidget> with AutomaticKeepAliveClientMixin{
   ...

   @override
   bool get wantKeepAlive => true;
  }

此处有更多信息:https://docs.flutter.io/flutter/widgets/AutomaticKeepAliveClientMixin-mixin.html