0

My addSteps function require access to the context. I have a repository object that is stored here.

 Future<int> _addSteps() async {
     repository = RepositoryProvider.of<lo.Repository>(context);
     ...
 }

The future _addStepsFuture is created in didChangeDependencies.

didChangeDependencies() {
     addStepsFuture = _addSteps();
}

Although the context is recived later in the Build call.

FutureBuilder<int>(
          future: _addStepsFuture,
)

The BuildContext is not available until Build is called.

Is there a way to solve this problem? Thank you.

  • Could you add more example code? What exactly are you wanting to do with the the `BuildContext`? `context` should be available inside `didChangeDependencies`. See this [SO answer](https://stackoverflow.com/a/49458289/8213910) – Nolence Dec 03 '19 at 17:20
  • I have added some more code above. – Rajitha Wijayaratne Dec 04 '19 at 03:47

1 Answers1

1

You can access context in didChangeDependencies since your RepositoryProvider.of call is just using inheritFromWidgetOfExactType under the hood.

But unless you have a different reason for using the didChangeDependencies lifecycle hook, you could also try:

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final repository = RepositoryProvider.of<lo.Repository>(context);

    return FutureBuilder(
      future: _addSteps(repository),
      builder: (context, snapshot) {
        return Placeholder();
      },
    );
  }

  Future _addSteps(lo.Repository repository) async {
    /* ... */
  }
}

or

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _addSteps(context),
      builder: (context, snapshot) {
        return Placeholder();
      },
    );
  }

  Future _addSteps(BuildContext context) async {
    final repository = RepositoryProvider.of<lo.Repository>(context);
    /* ... */
  }
}

Let me know if I misunderstood the problem

Nolence
  • 2,134
  • 15
  • 25
  • Its not advised to do this -> future: _addSteps(repository). The official instructions are -> The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. -> https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html – Rajitha Wijayaratne Dec 04 '19 at 14:37
  • I see. In that case, your initial code looks correct, no? Is there an error it's throwing? `RepositoryProvider` simply calls the `Provider` [package's `Provider.of(context, listen: false`)](https://github.com/felangel/bloc/blob/abb04a1813b3d81098ed38d438cc5562d95ce28f/packages/flutter_bloc/lib/src/repository_provider.dart#L50) which doesn't need a special context (i.e. it doesn't need the context provided passed to `build`) so long as you've provided the repository somewhere above – Nolence Dec 04 '19 at 15:19