'Navigation to screen with Flutter Hooks not working

Navigating from a button press to a screen with HookConsumerWidget or HookWidget gives an error: "Hooks can only be called from within the build method of a widget that mix-in hooks".

But I thought the button that navigates to the screen is already within the build method of the calling screen. I converted the calling screen to a HookWidget just in case that was the issue but no lukc as I get the same error. I am not understanding this error.

snippet in a stateless widget containing button to navigate:

_BackLayerButton(
                  icon: Icons.upload,
                  title: 'Upload Product',
                  onPressed: () {
                    Navigator.of(context)
                        .pushNamed(UploadProductScreen.routeName);
                  },
                ),

UploadProducScreen that is final destination:

class UploadProductScreen extends HookConsumerWidget {
  static const routeName = 'uploadProductScreen';
  UploadProductScreen({Key? key}) : super(key: key);
  final GlobalKey<FormState> _formKey = GlobalKey();
  final _file = useState<File?>(null);
  final _imageFile = useState<XFile?>(null);
  final _imagePicker = ImagePicker();


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final category = ref.watch(categoryControllerProvider).productCategory;
    String _productTitle = '';

When I replace the above code with a simple Stateless widget, everything works. How can one navigate to a screen with Hooks via button pressed from another screen? Please help as I have tried everything I know to do. The same code works for stateless and stateful widgets for navigation but not for HookWidget. I need to use hooks for other features of the app so abandoning hooks is not my choice. Thanks a million.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source