我是Flutter的新手,目前正在练习。我正在从官方文档中学习,并且自己尝试(删除操作)。但是为什么不告诉我是行不通的。我只是想了解结构,因此我在阅读了官方文档后尝试了此方法。但它显示错误。我回到文档,我找不到我的错误在哪里,请帮忙
import 'package:flutter/material.dart';
class Product {
Product({this.name});
final String name;
}
class Item extends StatelessWidget {
Item({this.product});
final Product product;
@override
Widget build(BuildContext context) {
return ListTile(
leading: CircleAvatar(
child: Text(product.name[0]),
),
title: Text(product.name),
);
}
}
class MyShoppingList extends StatefulWidget {
MyShoppingList({this.products});
final List<Product> products;
@override
_MyShoppingListState createState() => _MyShoppingListState();
}
class _MyShoppingListState extends State<MyShoppingList> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Shopping List"),
),
body: Column(
children: <Widget>[
ListView(
children: widget.products.map((Product product) {
Item(product: product);
}).toList(),
)
],
),
);
}
}
main() {
return runApp(MaterialApp(
home: MyShoppingList(
products: <Product>[
Product(name: "Hello"),
Product(name: "World"),
Product(name: "")
],
),
));
}
您的代码中有3个问题:
第一:您在列内使用listView,并且两者都有无限制的高度。
解决方案:例如,您可以将listview包装Expanded
为如下所示:
Column(
children: <Widget>[
Expanded(
child: ListView(
children: widget.products.map((Product product) {
return Item(product: product);
}).toList(),
),
)
],
)
第二个问题:您需要在map方法内使用return关键字。
ListView(
children: widget.products.map((Product product) {
// You need to return the Item widget here.
return Item(product: product);
}).toList(),
),
第三个问题:您试图显示窗口小部件product.name
内部的第一个字符,listTile
有时可能为null,因此必须检查是否product.name
为null
第一个。
解
ListTile(
leading: CircleAvatar(
child: Text(
product.name == null || product.name == "" ? " " : product.name[0]),
),
title: Text(product.name),
)
最终代码将是:
import 'package:flutter/material.dart';
class Product {
Product({this.name});
final String name;
}
class Item extends StatelessWidget {
Item({this.product});
final Product product;
@override
Widget build(BuildContext context) {
return ListTile(
leading: CircleAvatar(
child: Text(
product.name == null || product.name == "" ? " " : product.name[0]),
),
title: Text(product.name),
);
}
}
class MyShoppingList extends StatefulWidget {
MyShoppingList({this.products});
final List<Product> products;
@override
_MyShoppingListState createState() => _MyShoppingListState();
}
class _MyShoppingListState extends State<MyShoppingList> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Shopping List"),
),
body: Column(
children: <Widget>[
Expanded(
child: ListView(
children: widget.products.map((Product product) {
return Item(product: product);
}).toList(),
),
)
],
),
);
}
}
main() {
return runApp(MaterialApp(
home: MyShoppingList(
products: <Product>[
Product(name: "Hello"),
Product(name: "World"),
Product(name: "")
],
),
));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句