Flutter: How to access 'provider' values in a function outside the build context of the child widget?
You can read the variables from your provider like this: Provider.of(context, listen: false).yourVariable
in getHomeCampaigns
. You must have listen: false
for this to work though because it is not in the widget tree so it can't update whenever yourVariable
changes -- see . If this doesn't work there is a problem where you declare you provider. If this works please up vote and accept as answer, otherwise comment below.
I moved from my api being an inheritedWidget to a provider. "The Flutter Complete Reference" suggested to avoid inheritWidget because of complexity. I start at the materialapp and wrap it around my api class containing my restful calls. I use the counter to see that the button has been pressed. Now, I can access my api calls in all objects in the materialapp tree.
void main() { runApp(MyApp());}class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp( title: 'My app', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Provider<Api>( create: (context) => Api(), child: Home(title: 'my title'))); }}class Home extends StatefulWidget { Home({Key key, @required this.title}) : super(key: key); final String title; @override _HomeState createState() => _HomeState(); }class _HomeState extends State<Home> { int _counter = 0; onLogin(BuildContext context) { LoginView param = new LoginView("abc@com", "xxx"); Provider.of<Api>(context, listen: false) .addLogin(context, param) .then((value) { setState(() { _counter++; }); }).catchError((error) { DialogCaller.showErrorDialog(context, error.toString()).then((value) {});});} @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Example'), ), body: Container( child: Column( children: [ TextButton.icon( label: Text("abc"), icon: Icon(Icons.web), onPressed: () { onLogin(context); setState(() { _counter++; }); }), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ) ], ))); }}