使用 Flutter Hooks 导航到屏幕不起作用

Navigation to screen with Flutter Hooks not working

使用 HookConsumerWidget 或 HookWidget 从按钮按下导航到屏幕会出现错误:“Hooks can only be called from within a widget that mix-in hooks”。

但我认为导航到屏幕的按钮已经在调用屏幕的构建方法中。我将调用屏幕转换为 HookWidget 以防出现问题,但没有 lukc,因为我遇到了同样的错误。我不明白这个错误。

包含导航按钮的无状态小部件中的代码段:

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

作为最终目的地的 UploadProducScreen:

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 = '';

当我用一个简单的无状态小部件替换上面的代码时,一切正常。如何通过从另一个屏幕按下按钮导航到带有 Hooks 的屏幕?请帮忙,因为我已经尝试了我所知道的一切。相同的代码适用于用于导航的无状态和有状态小部件,但不适用于 HookWidget。我需要为应用程序的其他功能使用挂钩,所以放弃挂钩不是我的选择。百万感谢。

逐行梳理代码,经过排除过程,发现并解决了问题。该错误专门针对调用的 HookWidget class(屏幕),而不是调用屏幕。 我发现定义为使用 useTextEditingController() 的几个最终变量(例如 emailTextEditingController)是在小部件的构建方法之外定义的。一旦我将这些变量适当地重新定位到小部件的构建方法中,错误就会消失,并且导航会按预期进行。呸!!!这花了我 3 天,但感谢上帝的洞察力。我还有其他悬而未决的问题需要帮助解决;例如动画无法使用 HookWidget 工作,但可以在有状态 class.

中工作