Home > Mobile >  How to run async await code which is from store of provider inside initState
How to run async await code which is from store of provider inside initState

Time:06-01

I'm trying to get data from API when my app starts. Therefore, I wrote the async await function at a store of Provider to bring API data. However, it doesn't work and sends 404 status code. How can I fix this problem?

main.dart codes

@override
  void initState(){
    super.initState();
    // this is the code from provider
    context.read<HomeData>().getData();
  }

  @override
  Widget build(BuildContext context) {
    return  DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: TopAppBar(
        ),
        body: BodyPage(
          changePage : _changePage,
          pageController : _pageController,
          currentIndex : _currentIndex,
        ),
        bottomNavigationBar: BottomBar(currentIndex: _currentIndex, pageController: _pageController),
        extendBodyBehindAppBar: true,
      ),
    );
  }

Provider Store codes

class HomeData extends ChangeNotifier {
  var homeData = [];
  var boardItem = {};

  late String _image;
  String get image => _image;
  late String _content;
  String get content => _content;
  var _now;
  DateTime get now => _now;

  // 처음 홈에서 렌더링 될 때 나오는 아이템 데이터를 불러옴
  getData() async{
    var rawData = await http.get(Uri.parse('https://codingapple1.github.io/app/Constants.json'));
    if (rawData.statusCode == 200) {
      homeData = jsonDecode(rawData.body);
      print(homeData);
    }
    else{
      print('statusCode : ${rawData.statusCode}');
    }

    notifyListeners();
  }
}

CodePudding user response:

As the issue is 404 means page is not found(available). Try rechecking the link path.

You will find context issue until first frame gets build. You can use addPostFrameCallback.

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      await context.read<HomeData>().getData();
    });
  }

Also you can try using FutureBuilder.

CodePudding user response:

You can use FutureBuilder or WidgetsBinding or you can put it in your init state; Future.delayed(Duration.zero, ()async{await xx();},);

  • Related