import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: TestWidget())));
}
}
class TestWidget extends StatefulWidget {
TestWidgetState createState() => new TestWidgetState();
}
class TestWidgetState extends State<TestWidget> {
List<Widget> _bodyItems = [];
List<Widget> _topItems = [];
final Widget _boundary = Column(
children: <Widget>[
SizedBox(
height: 10,
),
SizedBox(
child: Container(
color: Colors.black12,
),
height: 1,
),
SizedBox(
height: 10,
),
],
);
@override
void initState() {
super.initState();
Widget e = GestureDetector(key: Key("0"), onTap: () {
onChangedFunction(Key("0"));
},child: Text("This text is on body range"));
_bodyItems.add(e);
_topItems = [];
}
void onChangedFunction(Key key) async {
setState(() {
_bodyItems.removeAt(0);
_topItems.add(Text("This text is on top range."));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
SizedBox(
height: 10,
),
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 100,
),
child: ListView(
scrollDirection: Axis.horizontal,
children: _topItems,
),
),
_boundary,
ConstrainedBox(
constraints: BoxConstraints(
minHeight: 450,
maxHeight: 450,
),
child: Column(
children: _bodyItems,
),
),
_boundary,
],
)));
}
}
结果
top items : [Text("This text is on top range.")]
当点击主体项目的窗口小部件并将其添加到顶部项目时,此代码将删除主体项目。
查看结果,您可以看到数据从主体项目小部件中消失了,并且该数据已添加到顶部项目小部件中。
但是,不会渲染顶层项目的数据。
我想知道原因是什么。
最佳答案
发生这种情况是因为Children是恒定的,如果您查看定义,就会看到。
您将在实现ListView的过程中找到以下行。
List<Widget> children = const <Widget>[],
但您可以更改旁边的子项中的小部件,因此必须将list作为list的子项。
随风飘扬。
children: [..._topItems],
关于flutter - flutter ,为什么在调用构建方法时不渲染ListView <Widget>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61721557/