はじめに
はじめましてCrazeです。こんにちは😉
Today, I had to copy and paste many, many identical screens using the ones in the list, but it was tough😭
What’s more, it makes the code more complicated😮💨
Like this
ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
TaskScreen(user: widget.user, task: tasks[0]),
TaskScreen(user: widget.user, task: tasks[1]),
TaskScreen(user: widget.user, task: tasks[2]),
TaskScreen(user: widget.user, task: tasks[3]),
TaskScreen(user: widget.user, task: tasks[4]),
],
)
It’s a bit messy, isn’t it?
I created five TaskScreens this time, but what if the number of widgets I had to make was 100 or 1000?
I don’t want to imagine it😅
Thus, I’ve found a way to solve this problem: the ListView.builder!!!!
Let’s show a sample and an example code of the ListView.builder
Sample Code
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.star),
title: Text(items[index]),
subtitle: Text('Item $index'),
);
},
)
Example Code
For practical, I tried to arrange as many screens as the ones in the list.
And this is my today’s effort
Let me show you☺️
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Product List Example')),
body: ProductList(),
),
);
}
}
class ProductList extends StatelessWidget {
// Sample list of products
final List<Map<String, String>> products = [
{'name': 'Apple', 'price': '\$1.00'},
{'name': 'Banana', 'price': '\$0.50'},
{'name': 'Carrot', 'price': '\$0.30'},
{'name': 'Donut', 'price': '\$2.00'},
{'name': 'Eggplant', 'price': '\$1.20'},
{'name': 'Fish', 'price': '\$5.00'},
{'name': 'Grapes', 'price': '\$2.50'},
{'name': 'Honey', 'price': '\$3.00'},
{'name': 'Ice Cream', 'price': '\$1.80'},
{'name': 'Juice', 'price': '\$2.20'},
];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: products.length, // Number of products
itemBuilder: (context, index) {
final product = products[index];
return Card(
child: ListTile(
leading: Icon(Icons.shopping_cart),
title: Text(product['name']!), // Product name
subtitle: Text('Price: ${product['price']}'), // Product price
),
);
},
);
}
}
This is the final form of this code
コメント