flutter state management
// providers/provider.dart
class Products with ChangeNotifier {
List<Product> _items = [
...dummy data
];
List<Product> get items {
return [..._items];
}
Product findById(String id) { //this func will be used for getting product with id
return _items.firstWhere((element) => element.id == id);
}
}
// main.dart (this needs to be the topmost file wwhose children need to access the state
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => Products(), // pass here the provider you want to access
child: MaterialApp(
title: 'Flutter Demo',
home: ProductsOverviewScreen(),
),
);
}
}
// in the file you want to access the state
class ProductDetailScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final productId = ModalRoute.of(context)!.settings.arguments as String;
final loadedProduct =
Provider.of<Products>(context).findById(productId);
return Scaffold(
appBar: AppBar(
title: Text(loadedProduct.title),
),
);
}
}