1

What is the best approach to calling an API or method when a screen wants to start in the Flutter app?

As I know in initState method, there is no context so I use didChangeDependencies method like below, but I always think there is a better way to tackle this issue. Any idea, snippet, or sample project link will be appreciated.

class HomeTabScreen extends StatefulWidget {
  static String route = 'accountTab';

  @override
  _HomeTabScreenState createState() => _HomeTabScreenState();
}

class _HomeTabScreenState extends State<HomeTabScreen> {
  late HomeTabViewModel homeTabVM;
  var firstTime = true;

  late TabController _controller;

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

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

    if (firstTime) {
      homeTabVM = context.watch<HomeTabViewModel>();
      homeTabVM.getUserData(context);

      _controller = TabController(
        length: homeTabVM.list.length,
        vsync: this,
        initialIndex: 1,
      );

      firstTime = false;
    }

    homeTabVM.listKey = GlobalKey();
    homeTabVM.listItems.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      color: Colors.transparent,
      child: Center(
        child: CircularProgressIndicator(),
      ),
    ));
  }
}
JustAG33K
  • 1,403
  • 3
  • 13
  • 28
Davoud
  • 2,576
  • 1
  • 32
  • 53
  • see if this helps: https://stackoverflow.com/questions/55956707/how-do-i-access-buildcontext-outside-of-a-stateful-or-stateless-widget – Benyamin Oct 04 '21 at 14:56
  • This might also help: https://stackoverflow.com/questions/49457717/flutter-get-context-in-initstate-method?noredirect=1&lq=1 – Lulupointu Oct 04 '21 at 16:07

0 Answers0