我试图把ListView.builder部件放在一个Column部件中,但是flutter团队提供的常见解决方案是把未绑定的ListView.builder放在一个Expanded或Flexible部件中。这样做的问题是ListView.builder现在在列中占据了尽可能多的空间(如图所示)。
有没有办法让ListView.builder只占用它需要的空间?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Text> lst = [Text('first'), Text('second')];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ListView',
home: SafeArea(
child: Scaffold(
body: Column(
children: <Widget>[
Flexible(
child: ListView.builder(
itemCount: lst.length,
itemBuilder: (context, index) {
return Center(
child: lst[index],
);
},
),
),
FlatButton(
color: Colors.blue,
child: Text("Add Third"),
onPressed: () {
setState(() {
lst.add(Text("Third"));
});
},
),
Text("Next Item"),
],
),
),
),
);
}
}
你可以使用 shrinkWrap: true 属性来限制列表视图的大小。
child: ListView.builder(
shrinkWrap: true, //added line
itemCount: lst.length,