Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed

前端 未结 7 1442
半阙折子戏
半阙折子戏 2021-02-18 16:46

I am calling initial method to load data from API using initState. But it is resulting me an error. Here is error:

Unhandled Exception: inheritFromWidgetOfExactT         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-18 17:40

    Use after_init package to handle this issue

    Adds a didInitState() lifecycle method to stateful widgets where you can safely access inherited widgets.

    InheritedWidget is heavily used throughout the Flutter framework. Many state management packages such as ScopedModel and Provider use it as well. Unfortunately, InheritedWidgets are not accessible from the initState() method of State.

    Example:

    import 'package:flutter/material.dart';
    import 'package:after_init/after_init.dart';
    
    void main() {
      runApp(
        MaterialApp(
          home: Scaffold(
            body: Example(),
          ),
        ),
      );
    }
    
    class Example extends StatefulWidget {
      @override
      _ExampleState createState() => _ExampleState();
    }
    
    class _ExampleState extends State with AfterInitMixin {
      Size size;
    
      /// This gets called first, as usual.
      @override
      void initState() {
        super.initState();
        // Your code here
      }
    
      /// This gets called after initState(), only once.
      /// Safely access inherited widgets here.
      @override
      void didInitState() {
        // No need to call super.didInitState().
        // setState() is not required because build() will automatically be called by Flutter.
        size = MediaQuery.of(context).size;
      }
    
      /// This gets called after didInitState().
      /// And anytime the widget's dependencies change, as usual.
      @override
      void didChangeDependencies() {
        super.didChangeDependencies();
        // Your code here
      }
    
      /// Finally this gets called, as usual.
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Text(size.toString()),
        );
      }
    }
    

提交回复
热议问题