颤振:来回切换筛选器时,项目从ListView中消失;滚动时,滚动条抽动

时间:2020-02-13 15:30:25

标签: listview flutter filtering scrollbar

当我尝试实施简单的ListView过滤时,我遇到了两个困难。

  1. 当项目不满足过滤规则时,我首先返回高度为零的Container并起作用,但是当我过滤一部分项目,然后向下滚动,禁用过滤器并向后滚动时,先前过滤的项目不再出现:

filtering bug

然后我返回了高度为0.0001的Container,问题得到了意外解决:

filtering bug solved

为什么这样做有效?高度为{01}的Container也与高度为零的Container一样不可见。 还有更好的解决方案吗?

  1. 滚动过滤时,我过滤了数百个Scrollbar抽搐:

scrollbar twitching

应用过滤器后,如何使Scrollbar流畅?

Code in DartPad

代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final items = List.generate(1000, (index) => '$index');
  var filterOptions = List.of(IntType.values);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: buildBody(),
        appBar: AppBar(
          title: Text('Simple filtering'),
          bottom: buildAppBarBottom(),
        ),
      ),
    );
  }

  Widget buildBody() {
    return Scrollbar(                       // second question
      child: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];

          if (filterOptions.any((option) => option.length == item.length)) {
            return ListTile(title: Text(item));
          }

          return Container(height: 0.0001); // first question
        },
      ),
    );
  }

  PreferredSizeWidget buildAppBarBottom() {
    return PreferredSize(
      preferredSize: Size.fromHeight(50),
      child: Padding(
        padding: EdgeInsets.all(8),
        child: Row(
          children: IntType.values.map((option) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 4),
              child: FilterChip(
                selectedColor: Colors.white,
                selected: filterOptions.contains(option),
                onSelected: (isSelected) {
                  setState(() {
                    if (isSelected) {
                      filterOptions.add(option);
                    } else {
                      filterOptions.remove(option);
                    }
                  });
                },
                label: Text(option.name),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class IntType {
  static const IntType ones = const IntType._('Ones', 1);
  static const IntType tens = const IntType._('Tens', 2);
  static const IntType hundreds = const IntType._('Hundreds', 3);

  final String name;
  final int length;

  const IntType._(this.name, this.length);

  static const values = [
    IntType.ones,
    IntType.tens,
    IntType.hundreds,
  ];
}


0 个答案:

没有答案