skip to Main Content

How to make an api request every time the screen opens? Now, after the first opening, the screen is saved, and you can update it only by pressing a button or swiping up. How to do this automatically, so that every time you open the screen, a request to the API is executed and the screen is updated?

I tried to use need_resume, but it also doesn’t work as I need it

2

Answers


  1. Turn it into a StatefulWidget and use initState
    The framework will call this method exactly once for each State object it creates.
    More information check the documentation

    @override
    void initState() {
        super.initState();
        // API here
    }
    
    Login or Signup to reply.
  2. There’s a specific package for such a thing. The package name is after_layout. This Package was developed by the official Flutter community.

    It’s mainly used in asynchronous functions calling while opening the screen. It’s the best approach because it does not disrupt the initial widget-building stage. While the initState is not for asynchronous calling.

    Sample code:

    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> with AfterLayoutMixin<HomePage> {
    
      @override
      void initState() {
        super.initState();
      }
    
      @override
      void dispose() {
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    
      @override
      FutureOr<void> afterFirstLayout(BuildContext context) async {
        // Make your API call here. It's the safest area & it's a greatest approach.
        return Future<void>.value();
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search