Navigator.pop(context,"return data") on listItem builder item click showing blank

Viewed 30

While selecting items from the list and pop back to the previous screen with selected item data I faced a black screen issue. Here is the code base:

Navigate from the parent screen

   final result = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const AddRoomPage()),
                    );

And here is the pop code

ListView.builder(
                  primary: false,
                  shrinkWrap: true,
                  padding: const EdgeInsets.all(20.0),
                  itemCount: roomNames.length,
                  itemBuilder: (BuildContext context, index) {
                    return GestureDetector(
                        onTap: () {
                          Navigator.pop(context, roomNames[index]);
                          },
                        child: RoomTypeItem(
                          roomName: roomNames[index],
                        ));
                  })

How do I get rid of the black screen? I used the same code to pop back on Text click it doesn’t give a black screen but clicking on listview item gives an issue.

1 Answers

You need to make sure that pop event is happening just single time, I think on your snippet it is using pop more than once.

You can follow this snippet structure.

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final result = await Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const AddRoomPage()),
          );

          print(result);
        },
      ),
    );
  }
}

class AddRoomPage extends StatefulWidget {
  const AddRoomPage({Key? key}) : super(key: key);

  @override
  State<AddRoomPage> createState() => _AddRoomPageState();
}

class _AddRoomPageState extends State<AddRoomPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Navigator.pop(context, "item $index");
            },
            child: Text("item $index"),
          );
        },
      ),
    );
  }
}

Related