虽然 IntrinsicWidth 适用于 Column,但我无法使其适用于 ListView.builder。也许我可以用 SingleChildScrollView 包装列,但这是另一个故事,它可以与 ListView.builder 一起使用吗?
这是我的代码:
// IntrinsicWidth not working with ListView
import 'package:flutter/material.dart';
void main(){
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('app'),backgroundColor: Colors.blue,),
body: Center(
child: IntrinsicWidth(
child: ListView.builder(
//physics: const NeverScrollableScrollPhysics(),
itemCount: ls.length,
itemBuilder: (context, index){
return Center(
child: Container(
color: Colors.yellow.shade200,
margin: const EdgeInsets.symmetric(vertical: 2),
child: Text(ls[index],style: const TextStyle(fontSize: 30)),
),
);
},
),
),
),
);
}
}
List<String> ls =[
"John Doe",
"Jane Smith",
"Michael Johnson",
"Emily Davis",
"William Brown",
"Olivia Taylor",
"James Wilson",
"Emma Jones",
"Oliver Carter",
"Ava Lee",
];
我收到以下错误:
/* 在performLayout()期间抛出以下断言: RenderViewport 不支持返回内在尺寸。 */
/* 在performLayout()期间抛出以下断言: 'package:flutter/src/rendering/shifted_box.dart': 断言失败: 第 345 行 pos 12: 'child!.hasSize': 不正确。 */
内在宽度与listview.builder无关,因为内在宽度的概念是小部件根据其内容而采用的自然宽度,与ListView等可滚动小部件无关,因为它们会扩展以填充可用空间。而不是 你应该使用shrinkWrap。只需在listview.builder中添加shrinkWrap: true