由于我们不知道您对 Product 和 ProductList 的实现细节,我自己在这种情况下创建了一个示例。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Product
{
final String name;
final String id;
final List<String> ingredients;
const Product({
required this.name,
required this.id,
required this.ingredients
});
}
class ProductList extends ChangeNotifier
{
final _products = <Product>[];
void add(Product product)
{
_products.add(product);
notifyListeners();
}
Iterable<Product> get products => _products;
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => ProductList()),
],
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
context.read<ProductList>().add(const Product(name: 'Product 1', id: '1234', ingredients: ['Hello', 'There']));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: const SafeArea(
child: Products(),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class Products extends StatelessWidget {
const Products({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for(var product in context.watch<ProductList>().products)
ListTile(
leading: Text(product.id),
title: Text(product.name),
subtitle: Text(product.ingredients.join(', ')),
),
]
);
}
}
您可以在Dart Pad 上查看。希望这可以帮助。请参考How to create a Minimal, Reproducible Example。