1

I am working on a flutter application and I have an Inherited Widget class. There is a function in my InheritedWidget Class which needs to access BuildContext. Is it possible to access context(BuildContext) from widget object? If yes, what are the ways to access it.

class ApiClient extends InheritedWidget{

  final String baseUrl;

  ApiClient({
    @required this.baseUrl,
    @required Widget child
  }):super(child:child);

  static ApiClient of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(ApiClient);
  }

  Future<http.Response> login(String email, String password){

    Map<String, String> body = {
       "username":email,
       "password":password,
       "client_secret": //This I want to read from an EnvironmentConfig
 //file which is also an InheritedWidget And In order to read that I need context,
    };
    return _network.post(baseUrl+ApiEndpoints.LOGIN, body:json.encode(body), headers: ApiHeaders.headers);
  }



  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => false;


}
vipin agrahari
  • 2,691
  • 3
  • 21
  • 31
  • Can you share your widget? You're likely to be doing something wrong – Rémi Rousselet Oct 03 '18 at 14:20
  • @RémiRousselet I have added related code snippet. – vipin agrahari Oct 03 '18 at 14:25
  • 1
    As I expected. You should not have any logic inside your InheritedWidget. It should be used *only* to hold variables. You will need to combine it to a StatefulWidget; See https://stackoverflow.com/questions/49491860/flutter-how-to-correctly-use-an-inherited-widget/49492495?s=5|63.2436#49492495 – Rémi Rousselet Oct 03 '18 at 14:28
  • @RémiRousselet However I want to have some functions in my InheritedWidget. Is it a bad practise to put them in InheritedWidgets? – vipin agrahari Oct 03 '18 at 14:41
  • There is not point in having them here. You can make your static `of` method return the State instead, and add your methods there. – Rémi Rousselet Oct 03 '18 at 14:44

0 Answers0