如何使用顫振顯示具有多種型別的串列視圖,例如(第 1 項:文本,第 2 項:帶文本的影像......)?
這是代碼:我需要讓 ListView 在 item1 中顯示 onlyText,在 item2 中顯示 imageWithText 等等,我該怎么做?
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
SizedBox(height: 5),
ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) => onlyText(),
separatorBuilder: (context, index) => SizedBox(height: 10),
itemCount: 100,
),
],
),
);
}
}
Widget imageWithText() => Container(
child: Card(
child: Row(
children: [
Text(
'sara ahmad',
style: TextStyle(fontSize: 16),
),
SizedBox(width: 10),
Image.network(
'https://th.bing.com/th/id/R.e3a5da5209f4c39f1899456c94371a6f?rik=mz9sVBWxRJKGgA&riu=http://media1.santabanta.com/full1/Animals/Horses/horses-62a.jpg&ehk=o/S9l8DSJtUbl+YcrwLMJy6W4MfUby7bTUHRwJu7a+U=&risl=&pid=ImgRaw&r=0',
width: 100,
height: 100,
),
],
),
),
);
Widget onlyText() => Container(
child: Card(
child: Row(
children: [
Text(
'sara ahmad',
style: TextStyle(fontSize: 16),
),
SizedBox(width: 10),
Text('Nour'),
],
),
),
);
uj5u.com熱心網友回復:
///crete an empty widget list
List<Widget> item_list=[];
///create a function to add data to list and call this function in the initstate
add_items_to_list()async{
item_list.add(Text(('data')));
item_list.add(Image.asset('name'));
///add as much as you want
}
///use widget as below
Widget items()=>ListView(
children: item_list,
);
uj5u.com熱心網友回復:
如果你想顯示靜態串列,你可以這樣做
itemBuilder: (context, index) => index.isEven
? onlyText()
: imageWithText(),
或者你有動態資料然后按照下面
假設您有這樣的Model class串列
class Model{
String text,
String img,
}
var list = <Model>[]; //your data will be here
并檢查是否只有影像,你需要像下面這樣的條件,所以ListView你可以像這樣檢查
itemBuilder: (context, index) => list[index].img == null
? onlyText()
: imageWithText(),
uj5u.com熱心網友回復:
在 中,itemBuilder您可以檢查該專案是否只是帶有
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
SizedBox(height: 5),
Expanded(
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) =>
index == 0 ? onlyText() : imageWithText(),
separatorBuilder: (context, index) => SizedBox(height: 10),
itemCount: 100,
),
),
],
),
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/495492.html
