Search code examples
flutterfunctionclassdartflutter-widget

How to pass 'context' to another widget outside buildContext widget


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


Solution

  • try this: Widget buildUser(User user, BuildContext context) =>