我在使用 Flutter 代码时遇到问题。我正在尝试在自定义小部件中实现 ListView 构建器,但收到一条错误消息:“期望类型为 '(Object) => Widget' 的值,但得到类型为 '(String) = 的值” > 大小框'。尽管我尝试调整函数类型,但错误仍然存在。
在自定义小部件中使用 ListView 构建器时,我的 Flutter 应用程序遇到问题。我收到的错误消息是:“预期为‘(Object) => Widget’类型的值,但得到了‘(String) => SizedBox’类型的值。”我提供了下面的代码来说明问题。我尝试调整函数类型,但错误仍然存在。有人可以帮助我理解并解决这个问题吗?
const ContentDesktopAdminView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: max(560, 560),
width: 1000,
child: SingleChildScrollView(
child: Column(
children: [
AnyPage(
articles: [
Article(
lastModified: DateTime.now(),
name: 'Something',
),
],
),
],
),
),
),
],
),
),
);
}
}
class ListViewColumn<T> extends StatelessWidget {
const ListViewColumn({
required this.itemList,
Key? key,
}) : super(key: key);
final List<ListModel<T>> itemList;
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
...itemList.map(
(e) => Column(
children: [
if (e.columnHeaderCell != null)
e.columnHeaderCell!(e.columnName ?? '')
else
Text(e.columnName ?? ''),
SizedBox(
width: 100.pw,
height: 100.pw,
child: ListView.builder(
itemCount: e.list.length,
itemBuilder: (BuildContext context, int index) =>
e.cell(e.list[index]),
),
),
],
),
),
],
),
],
);
}
}
class ListModel<T> {
ListModel({
required this.list,
required this.cell,
this.columnName,
this.columnHeaderCell,
});
final String? columnName;
final List<T> list;
final Widget Function(T value) cell;
final Widget Function(String value)? columnHeaderCell;
}
class AnyPage extends StatelessWidget {
const AnyPage({required this.articles, Key? key}) : super(key: key);
final List<Article> articles;
@override
Widget build(BuildContext context) {
return ListViewColumn(
itemList: [
ListModel(
list: articles.map((e) => e.name).toList(),
columnName: 'Title',
cell: (value) => SizedBox(
height: 20,
width: 100,
child: Text(value),
),
),
ListModel(
list: articles.map((e) => e.lastModified).toList(),
columnName: 'Last modified',
cell: (value) => SizedBox(
height: 20,
width: 100,
child: Text(value.toIso8601String()),
),
),
],
);
}
}
class Article {
Article({
required this.lastModified,
required this.name,
});
final String name;
final DateTime lastModified;
}
首先文章似乎是一个类,您正在尝试手动实现列表视图。如果您尝试创建列表视图,请改用 ListView.builder 小部件。您可以在此处查看可用的所有类型的列表视图
假设您可以定义一个文章列表,您可能想要使用这样的东西。
ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
return MyCustomArticleWidget(article: articles[index]);
},
);
如您所见,我正在访问每个项目并将文章传递给 MyCustomArticleWidget,这是一个以文章作为参数的小部件。您可以像这样定义无状态小部件
class MyCustomArticleWidget extends StatelessWidget {
final Article article;
const MyCustomArticleWidget({
super.key,
required this.article,
});
@override
Widget build(BuildContext context) {
return Text(article.name);
}
}