Home > Enterprise >  how to pass context outside stless and staful class flutter
how to pass context outside stless and staful class flutter

Time:08-25

I want to use context in constant files e.g

class StatusCodes {  
    static Map<int, String> overTimeCancelResponse = {
    0: "OverTime request Cancel Successfully",
    1: "Error Cancelling OverTime Request",
  }; 
}

or 
   
   class StatusCodes {
   static Map<int, OverTimeResponses> overTimeResponse = {
   0: OverTimeResponses(
      "Overtime Request Submitted Successfully",
       Colours.green,
     ),
   };
}

I am using a language file to change eng to a different Language like this e.g

class StatusCodes {  
    static Map<int, String> overTimeCancelResponse = {
    0: S.0f(context).cancel_request,
    1: S.0f(context).error,
  }; 
}

but I am not been able to use context here

CodePudding user response:

You can create a Map function function, pass the context through parameters and return your map

See the below code

class StatusCodes {
  Map<int, String> overTimeCancelResponse(BuildContext context) {
   return {
     0: "OverTime request Cancel Successfully", // you can pass a value with context here
     1: "Error Cancelling OverTime Request",
  };
 } 
}

CodePudding user response:

Maybe you shouldn't, but if you "must" this is the closest you can get:

class StatusCodes {

    static Map<int, String> getOverTimeCancelResponse(BuildContext context) {
      // Do something with context
      // ....
      // build your new "overTimeCancelResponse"
      return newOverTimeCancelResponse;
    }
}

It is not possible to use BuildContext (or any other variable) in a static variable.

  • Related