flutterlistscreenstatefulstatefulwidget

How to pass a list from second screen to first screen in flutter?


I have a stateful widget in my first and second screen. I have a list in my second screen and want to pass it to my first screen.

How to do it ?

I know how to pass a single data between screens but it didn't work for a list.


Solution

  • Navigator.push( is a future method, you can wait until it pop.

    On First page

    final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const SecondScreen(),
        ));
      data = result;
    setState(() {});
    

    And on second page while pop.

    final data = List.generate(33, (index) => index);
    Navigator.of(context).pop(data);
    

    Example snippet

    void main() => runApp(
          MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: FirstScreen(),
          ),
        );
    
    class FirstScreen extends StatefulWidget {
      const FirstScreen({super.key});
    
      @override
      State<FirstScreen> createState() => _FirstScreenState();
    }
    
    class _FirstScreenState extends State<FirstScreen> {
      List<int> data = [];
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView.builder(
            itemCount: data.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(data[index].toString()),
              );
            },
          ),
          floatingActionButton: FloatingActionButton(onPressed: () async {
            final result = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const SecondScreen(),
                ));
            data = result;
            setState(() {});
          }),
        );
      }
    }
    
    class SecondScreen extends StatelessWidget {
      const SecondScreen({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ElevatedButton(
              onPressed: () {
                final data = List.generate(33, (index) => index);
                Navigator.of(context).pop(data);
              },
              child: Text("pop")),
        );
      }
    }