I am trying to use the ViewModelWidget
class from the stacked package. I am able to show the TextWidget
which extends ViewModelWidget
in the body of the page, but cannot show it in the bottom sheet because I am showing the bottom sheet from the onPressed
function and that function does not have access to the view model.
Here is the code:
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyView(),
);
}
}
class MyViewModel extends BaseViewModel {
String title = 'Hello';
void updateTitle() {
title = 'Bye';
notifyListeners();
}
}
class MyView extends StatelessWidget {
const MyView({super.key});
@override
Widget build(BuildContext context) {
return ViewModelBuilder<MyViewModel>.reactive(
viewModelBuilder: () => MyViewModel(),
builder: (context, model, child) => Scaffold(
appBar: AppBar(
title: const Text('My View'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const TextWidget(),
ElevatedButton(
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return const SizedBox(child: Center(child: TextWidget(),), height: 200,);
},
);
},
child: const Text('Show Modal'),
),
],
),
),
);
}
}
class TextWidget extends ViewModelWidget<MyViewModel> {
const TextWidget({super.key});
@override
Widget build(BuildContext context, MyViewModel viewModel) {
return Text(viewModel.title);
}
}
And here's the error that happens when I try to open the bottom sheet:
How can I solve this error?
I think i got it
As a result you should give a try to return
ViewModelBuilder<HomeViewModel>.nonReactive(
Check the doc #Non Reactive : https://pub.dev/packages/stacked