Flutter getx控制器获取当前页面上下文。

8

我想在getxcontroller方法中使用上下文展示cool alert的自定义对话框。我创建了以下控制器:

class HomePageController extends GetxController {
 
   @override
   void onInit() {
     super.onInit();
     getData();
   }

   void getData(){
    //perform http request here 
     //show cool alert 

     CoolAlert.show(
      context: context,  //here needs the build context
      type: CoolAlertType.success
      );
   }

}

我正在无状态小部件中使用此控制器,示例如下:

class HomePage extends StatelessWidget {
   HomePage({ Key? key }) : super(key: key);

   final _c = Get.find<HomePageController>();


    @override
    Widget build(BuildContext context) {
        return Container(
  
          );
    }
 }

如何在控制器中获取当前主页的BuildContext以便显示“酷炫提示”。


如果您想访问当前屏幕上下文,请在主页上初始化HomePageController。 - Salih Can
你找到解决方案了吗? - Alok Kumar
1
// 你可以在这里获取上下文 BuildContext?context = Get.context; - Roldan Unne Torralba
5个回答

2

如果您想显示需要上下文作为必需参数的对话框或 snackbar。您可以使用 Get.dialog()Get.snackbar,它们的功能与 showDialogshowSnackbar 相同,但不需要上下文或脚手架。


1

你可以在构造函数中添加上下文:

@override
Widget build(BuildContext context) {
  Get.put(HomePageController(context: context));
  return Container();
}

对于HomePageController:
注意:你需要用Future.delayed(Duration.zero)包装函数,否则会抛出错误。
class HomePageController extends GetxController {
  late BuildContext context;

  HomePageController({required this.context});
  
   void getData(){
     Future.delayed(Duration.zero,(){
       CoolAlert.show(
         context: context,  //here needs the build context
         type: CoolAlertType.success
       );
     });
   }
  ...
}


0
最近的Dart中有空值,为了弥补空值,使用感叹号标记:所以在这种情况下我们使用这个:

Get.context!


0

你可以简单地使用

Get.context

它将看起来像这样

class HomePageController extends GetxController {
 
   @override
   void onInit() {
     super.onInit();
     getData();
   }

   void getData(){
    //perform http request here 
     //show cool alert 

     CoolAlert.show(
      context: Get.context,  //here needs the build context
      type: CoolAlertType.success
      );
   }

}

-2

您需要在主页上像以下这样初始化控制器

class HomePage extends StatelessWidget {
   HomePage({ Key? key }) : super(key: key);

   final _c = Get.put(HomePageController())..getData(context);


    @override
    Widget build(BuildContext context) {
        return Container(
  
          );
    }
 }

这个操作将会调用 getData 函数,并移除 onInit 函数,同时在 getData 函数中传递 Buildcontext 上下文参数。


我该如何将上下文传递给控制器? - Geoff
@Geoff,我已经修改了我的答案,请检查一下。 - MORE AKASH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接