【发布时间】:2019-09-07 03:33:58
【问题描述】:
我有一个 ListView,我通过单击一个按钮来更改列表中的项目。现在的问题是,当我向下滚动到列表末尾然后单击按钮时,项目会发生变化,但列表的位置仍然相同(所以当我向下滚动并且我之前列表的第 2 项位于顶部,则新列表的第 2 项也将位于顶部)。 我想要的是列表再次从顶部开始,我必须再次向下滚动。
我的 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(),
),
),
],
),
));
}
}
【问题讨论】: