简体   繁体   中英

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 in my API request retrieved using provider. And I also need the BuildContext to show dialog box on API request return. Is it ok to save the id and context globally or outside the class just like the sample code below? Please teach me how to do this the correct way.

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));
    }
  }

That static is a rabbit hole you should not follow. Just don't make it static in the first place.

PagewiseLoadController _pageLoadController; 

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

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

  // rest of your method here    
}

Now your getPage method can be a normal, non-static class method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM