Home > Software engineering >  How to pass 'context' to another widget outside buildContext widget
How to pass 'context' to another widget outside buildContext widget

Time:08-14

I have this code

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('All users'),
      ),
      body: StreamBuilder<List<User>>(
        stream: readUsers(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Text('error fetching data');
          } else if (snapshot.hasData) {
            if (snapshot.data!.isEmpty) {
              // return const Text('no data to fect');
              return Container(
                padding: const EdgeInsets.all(10.0),
                child: const Text('no data'),
              );
            } else {
              final users = snapshot.data!;
              return ListView(
                children: users.map(buildUser).toList(),
              );
            }
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
  }

Then at this point

 return ListView(
                children: users.map(buildUser).toList(),
              );

I want to return data from another widget outside buildContext widget but the issue here is that I don't know how to pass the 'context' in the users.map(buildUser).toList() unorder to eliminate the error in the image below.

enter image description here

CodePudding user response:

Recommended approach ->User helper widget instead of helper method.

or you can pass context as parameter to method

CodePudding user response:

Create a class like bellow

import 'package:flutter/material.dart';

class GlobalContextService { 
  static GlobalKey<NavigatorState> navigatorKey = 
  GlobalKey<NavigatorState>();
}

now assign this key to the MaterialApp in main.dart just like bellow

return MaterialApp(
navigatorKey: NavigationService.navigatorKey, // set property
);

Now you can access the context any where you want by using the following line of code

NavigationService.navigatorKey.currentContext
  • Related