Flutter Provider.of <>在子类中不起作用

时间:2019-09-21 11:39:54

标签: flutter

在我的应用程序中,当我在flutter主类中以StatefulWidgetStatelessWidgetState的形式使用它们时,此代码可以正常工作

final User user = Provider.of<User>(context);
final ConnectivityStatus connection = Provider.of<ConnectivityService>(context).connectivityStatus;

例如:

class FragmentMainApplicationBodyState extends State<FragmentMainApplicationBody>{

final User user = Provider.of<User>(context);
final ConnectivityStatus connection = Provider.of<ConnectivityService>(context).connectivityStatus;

@override
Widget build(BuildContext context)
  {
     return Text('${user.userController.userInfo.name}');
  }

}

现在我正在尝试在子类中使用它们,例如:

abstract class BaseState<T extends StatefulWidget> extends State {
  bool isOnline = true;
  ConnectivityStatus connection;
  User user ;

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

  Future _initConnectivity() async {
    connection = Provider.of<ConnectivityService>(context).connectivityStatus;
    isOnline = connection == ConnectivityStatus.Connected;
    user = Provider.of<User>(context);
  }
}

在类中实现它们时,Providers在此实现中不起作用

两个主题我都得到NULL

class FragmentMainApplicationBodyState extends BaseState<FragmentMainApplicationBody>{

  @override
  Widget build(BuildContext context)
  {
     return Text('${user.userController.userInfo.name}');
  }
}

MultiProvider结构:

ChangeNotifierProvider<User>.value(value: User()),
ChangeNotifierProvider<ConnectivityService>.value(value: ConnectivityService()),

用户

class User extends ChangeNotifier{
  UserController userController;
}

class UserController {
  UserInfo userInfo;
  PageInfo pageInfo;

  UserController(
      {@required this.userInfo,
      @required this.pageInfo,
      });
}

ConnectivityService

enum ConnectivityStatus { Connected, Disconnected }

class ConnectivityService extends ChangeNotifier {
  ConnectivityStatus connectivityStatus;

  ConnectivityService() {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) {
        connectivityStatus = isConnected ? ConnectivityStatus.Connected : ConnectivityStatus.Disconnected;
      });
      notifyListeners();
    });
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      return false;
    }
    return isConnected;
  }
}

0 个答案:

没有答案