Flutter - Update ListView and reset scroll position

时间:2019-04-17 00:15:07

标签: dart flutter

I have a ListView, where i change the Items in the List by clicking a button. Problem now is, that when i scroll down to the end of the list then click the Button, the Items change but the position of the list is still the same (so when i scrolled down and item #2 of my previous list was at the top, then item #2 of the new list will also be at the top). What i want is that the List starts at the top again and i have to scroll down again.

my main.dart:

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State<MyApp> {
  List _list;
  List _list1 = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'];
  List _list2 = ['Element A', 'Element B', 'Element C', 'Element D', 'Element E', 'Element F'];
  bool _isList1;

  @override
  void initState() {
    _list = _list1;
    _isList1 = true;
    super.initState();
  }

  void _changeList() {
    setState(() {
      if (_isList1) {
        _list = _list2;
        _isList1 = false;
      } else {
        _list = _list1;
        _isList1 = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Schürer',
        home: Scaffold(
          appBar: AppBar(
            title: Text('ListView'),
          ),
          body: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("Change List"),
                onPressed: _changeList,
              ),
              Expanded(
                child: ListView(
                  children: _list
                      .map(
                        (item) => Card(
                              child: Container(
                                padding: EdgeInsets.all(50),
                                color: Colors.black26,
                                child: Text(item),
                              ),
                            ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
        ));
  }
}

2 个答案:

答案 0 :(得分:2)

在这里,您必须向 ListView 提供,以区分两个不同的列表视图。如果您未提供,则flutter会认为两者都是相同的列表视图,并会使用其索引来跟踪列表视图。

如果我们将list的第一个元素作为键,那么在您的情况下可以解决的问题。

....
child: ListView(
              key: ObjectKey(_list[0]),
              children: _list
.....

答案 1 :(得分:1)

这项技术对我有用:

创建ScrollController变量:

ScrollController _scrollController = ScrollController();
...
...
_scrollController.animateTo(0, duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn);

这是flutteranimateTo()的描述:

从当前位置到给定值对位置进行动画处理。

只要更改textfield的值,我就调用此函数。