簡體   English   中英

如何在 flutter 中傳遞 static class 中的上下文或任何參數?

[英]How to pass context or any parameter in a static class in flutter?

I'm currently implementing pagination using pagewise package. But to use the pagecontroller , I have to define a static controller and static future function that will connect to my api using http. My problem is, I also need the current user id as a parameter在我的 API 請求中使用提供商檢索。 而且我還需要 BuildContext 在 API 請求返回時顯示對話框。 是否像下面的示例代碼那樣將id和context保存到全局或者class之外? 請教我如何以正確的方式做到這一點。

int id;
BuildContext currentContext;

class MyWidgetView extends StatefulWidget {
  @override
  _MyWidgetViewState createState() => _MyWidgetViewState();
}

class _MyWidgetViewState extends State<MyWidgetView> {
  bool _empty = false;

  @override
  void initState() {
    super.initState();
    currentContext = context;
    id = Provider.of<User>(context, listen: false).id;
    this._pageLoadController.addListener(() {
      if (this._pageLoadController.noItemsFound) {
        setState(() {
          this._empty = this._pageLoadController.noItemsFound;
        });
      }
    });
  }

  final _pageLoadController = PagewiseLoadController(
      pageSize: PAGE_SIZE, pageFuture: (pageIndex) => getPage(pageIndex));
      
  static Future<List<page>> getPage(int pageIndex) async {
    final APIService _pageService = APIService();
    final pages = await _pageService.getPage(id: id);
    if (pages.error == false) {
      return pages.data;
    } else {
      dialogBox(
          title: 'Error',
          message: pages.errorMessage,
          context: currentContext,
          isModal: true,
          function: () => Navigator.pop(currentContext));
    }
  }

那個static是一個你不應該跟隨的兔子洞。 只是不要一開始就把它static

PagewiseLoadController _pageLoadController; 

@override
void initState() {
  super.initState();

  _pageLoadController = PagewiseLoadController(pageSize: PAGE_SIZE, pageFuture: (pageIndex) => getPage(pageIndex));

  // rest of your method here    
}

現在您的getPage方法可以是普通的非靜態 class 方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM