在这个简单的类中,我希望使基本状态类能够管理一些操作,例如访问Internet连接:

abstract class BaseState<T extends StatefulWidget> extends State {
  bool isOnline;
  ConnectivityStatus _connectivityStatus;

  @override
  void initState() {
    super.initState();
    _connectivityStatus = Provider.of<ConnectivityStatus>(context);
    isOnline = _connectivityStatus == ConnectivityStatus.Connected;
    if (!isOnline) {
      showSimpleNotification(Text("disconnected"), background: Colors.green);
    } else {
      showSimpleNotification(Text("connected"), background: Colors.red);
    }
  }
}

当我尝试像这样使用此类时:
class _FragmentLoginState extends BaseState<FragmentLogin> with SingleTickerProviderStateMixin {
  PageController _pageController;
  Color left = Colors.black;
  Color right = Colors.white;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 1);
  }

  @override
  Widget build(BuildContext context) {
  }
}

最佳答案

Use a frame callback将执行延迟到下一帧(即initState完成后)

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

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _connectivityStatus = Provider.of<ConnectivityStatus>(context);
      isOnline = _connectivityStatus == ConnectivityStatus.Connected;
      if (!isOnline) {
        showSimpleNotification(Text("disconnected"), background: Colors.green);
      } else {
        showSimpleNotification(Text("connected"), background: Colors.red);
      }
    });
  }

关于flutter - 在之前调用了InheritFromWidgetOfExactType(InheritedProvider <ConnectivityStatus>)或inheritFromElement(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57955269/

10-12 04:47