当我尝试实施简单的ListView
过滤时,我遇到了两个困难。
Container
并起作用,但是当我过滤一部分项目,然后向下滚动,禁用过滤器并向后滚动时,先前过滤的项目不再出现: 然后我返回了高度为0.0001的Container
,问题得到了意外解决:
为什么这样做有效?高度为{01}的Container
也与高度为零的Container
一样不可见。
还有更好的解决方案吗?
Scrollbar
抽搐:应用过滤器后,如何使Scrollbar
流畅?
代码:
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,
];
}