0
我有我自己的带有ListView的StatelessWidget。我希望它的状态由父StatefulWidget管理。在无状态小部件中使用初始偏移量Flutter Listview
我希望的行为是,如果我改变一个值,listView滚动(或甚至跳转 - 没关系)到该值。
我认为如果每次调用parent的setState()方法时创建无状态小部件,带有initialOffset的scrollController将使列表“移动”,但它不会。值得一提的是,第一次构建initialOffset时应该如此。
这里是我的问题的示例代码:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 5;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new MyClass(_counter),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
child: new Icon(Icons.add),
),
);
}
}
class MyClass extends StatelessWidget {
final int extraValue;
final ScrollController scrollController;
MyClass(this.extraValue):
scrollController = new ScrollController(initialScrollOffset: extraValue*50.0);
@override
Widget build(BuildContext context) {
return new ListView.builder(
itemExtent: 50.0,
itemCount: 100,
controller: scrollController,
itemBuilder: (BuildContext context, int index) {
if (index != extraValue)
return new Text(index.toString());
else
return new Text("EXTRA" + index.toString());
});
}
}
我不知道这是否是一个错误或我的错误。
任何想法可能会有所帮助:)
编辑: 由伊恩·希克森的回答启发我解决我的问题:
void _incrementCounter() {
setState(() {
_counter++;
myClass.scrollController.animateTo(_counter*50.0, duration: new Duration(seconds: 1), curve: new ElasticOutCurve());
});
}
那么我怎样才能调用创建的小部件的动画方法?特别是在构建方法中,每次都创建一个新的方法? –
好的,我明白了。更新的问题。 –