0

我正在实施聊天,当项目从列表中删除时出现问题。如果我从 CustomScrollView 的底部删除多个项目,则滚动位置会根据删除项目的高度之和向上偏移。我该如何预防?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<int> list = List.generate(30, (i) => i + 1).reversed.toList();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            setState(() {
              list.removeRange(0, 5);
            });
          },
        ),
      ),
      body: CustomScrollView(
        reverse: true,
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  alignment: Alignment.center,
                  color: Colors.blue[200 + list[index] % 4 * 100],
                  height: 100,
                  child: Text('Item: ${list[index]}'),
                );
              },
              childCount: list.length,
            ),
          ),
        ],
      ),
    );
  }
}
4

1 回答 1

0

您可以使用

收缩包装:是的,

来解决你的问题。

它看起来像这样:

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<int> list = List.generate(30, (i) => i + 1).reversed.toList();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            setState(() {
              list.removeRange(0, 5);
            });
          },
        ),
      ),
      body: CustomScrollView(
        reverse: true,
        shrinkWrap: true,    // This line has changed
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  alignment: Alignment.center,
                  color: Colors.blue[200 + list[index] % 4 * 100],
                  height: 100,
                  child: Text('Item: ${list[index]}'),
                );
              },
              childCount: list.length,
            ),
          ),
        ],
      ),
    );
  }
}

之前:图像之前 之后:后像

于 2022-02-20T12:29:42.763 回答