Reputation: 13
Error: Could not find the correct Provider above this ProductScreen Widget
I'm getting this error trying to use MVVM in my flutter app. There is a provider above the ProductScreen that is ProductListViewModel and it should work in my opinion. If you can give me feedback I would appreciate it.
ChangeNotifierProvider usage:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Products",
debugShowCheckedModeBanner: false,
home:
ChangeNotifierProvider(
create: (context) => ProductListViewModel(),
child: ProductScreen(),
)
);
}
}
ProductListViewModel
class ProductListViewModel extends ChangeNotifier {
List<ProductViewModel> products = List<ProductViewModel>();
Future<void> fetchProducts(String keyword) async {
final results = await Webservice().fetchProducts(keyword);
this.products = results.map((item) => ProductViewModel.fromProduct(item)).toList();
notifyListeners();
}
}
ProductScreen
class ProductScreen extends StatefulWidget {
@override
_ProductScreenState createState() => _ProductScreenState();
}
class _ProductScreenState extends State<ProductScreen> {
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
// Provider.of<ProductListViewModel>(context, listen: false).fetchProducts("");
}
@override
Widget build(BuildContext context) {
final vm = Provider.of<ProductListViewModel>(context);
return Scaffold(
appBar: AppBar(
title: Text("Movies")
),
body: Container(
padding: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.only(left: 10),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(10)
),
child: TextField(
controller: _controller,
onSubmitted: (value) {
if(value.isNotEmpty) {
vm.fetchProducts(value);
_controller.clear();
}
},
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: "Search",
hintStyle: TextStyle(color: Colors.white),
border: InputBorder.none
),
),
),
Expanded(
child: ProductList(products: vm.products))
])
)
);
}
}
Upvotes: 1
Views: 191
Reputation: 420
wrap MaterialApp widget inside of ChangeNotifierProvider widget.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => ProductListViewModel(),
child: MaterialApp(
title: "Products",
debugShowCheckedModeBanner: false,
home: ProductScreen(),
)
);
}
}
or you can define it as mentioned in docs.
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => ProductListViewModel(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Products",
debugShowCheckedModeBanner: false,
home: ProductScreen(),
);
}
}
Also check out this medium blog for more info about provider, multiprovider and consumer.
Upvotes: 1