根据很多 Flutter provider 教程,建议使用 StatelessWidget 而不是 StatefulWidget with provider。但是在使用 StatelessWidget 时我找不到滚动 ListView 的方法。
假设我们有一个包含多行文本的 ListView,可以动态附加,并且应该始终滚动到中间行。像这样:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class MyData with ChangeNotifier {
List<String> _lines = [];
MyData() {
for (int i = 0; i < 100; i++) {
_lines.add("line $i");
}
}
List<String> get lines => _lines;
void add(line) {
_lines.add(line);
notifyListeners();
}
}
void main() {
MyData data = new MyData();
final app = ChangeNotifierProvider<MyData>.value(value: data, child: MyApp());
runApp(app);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: MyHomePage(),
);
}
}
class DataPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final _data = Provider.of<MyData>(context);
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: _data.lines.length,
itemBuilder: (context, index) {
return Text(_data.lines[index]);
}));
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final _data = Provider.of<MyData>(context);
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
_data.add("new line");
})
],
),
body: Center(child: Text("${_data.lines.length} lines")),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => DataPage())),
child: Icon(Icons.list),
));
}
}
添加新行时,有什么方法可以保持滚动到 ListView 的中间?