1

I have a CheckBox items selection screen (opened when Navigator.push is triggered in a floating button) to check the items that I like and I want these items to show on the screen when Navigator.pop is used (when a floating button is tapped) to go back to the original screen from where it originated. But I'm not able to do it, I think list.map will be used here but have I'm able to implement it properly. Any help is really appreciated.

You can check the entire code here.

My code where I've problem:

// CheckBox Item Selection Screen!
class FavoriteList extends StatefulWidget {
@override
_FavoriteListState createState() => _FavoriteListState();
}

class _FavoriteListState extends State<FavoriteList> {

final Set _saved = Set();

@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(title: Text('Add to Favorites!'), centerTitle:  true, backgroundColor: Colors.red),
  // backgroundColor: Colors.indigo,
  body: SafeArea(
          child: ListView.builder(
      itemCount: 53,
      itemBuilder: (context, index) {
        return CheckboxListTile(
          activeColor: Colors.red,
          checkColor: Colors.white,
          value: _saved.contains(index),
             onChanged: (val) {
              setState(() {
              if(val == true){
                _saved.add(index);
              } else{
                _saved.remove(index);
              }
            });
          },
          title: Row(
            children: <Widget>[
              Image.asset('lib/images/${images[index]}'),
              SizedBox(width: 10,),
              Text(nameOfSite[index]),
            ],
          ),
        );
      },
    ),
  ),
  floatingActionButton: FloatingActionButton(foregroundColor: Colors.red,
  child: Icon(Icons.check),
    onPressed: (){
      Navigator.pop(context, _saved); // Navigator.pop
    },
  ),
);
    }
   }

Here The original screen, to where I want to return the _saved list (i've used a Set as to avoid duplicates)

class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}


class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
  return 
   // if the `_saved` list contains something return the "_saved" list from 
   the CheckBox item selection screen, if not then 
    return  Column(
           mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
        Text(
           'Add Your Favorite Sites Here!❤',
           style: TextStyle(color: Colors.white),
           ),
           Container(
            child: Icon(Icons.favorite, size: 150, color: Colors.blue[100]),
          ),
          SizedBox(height: 250),
            FloatingActionButton(
             onPressed: () {
               Navigator.push( //Navigator.push is here!
                  context,
                   MaterialPageRoute(
            builder: (context) => FavoriteList(),
                ),
              );
           },
            child: Icon(Icons.add),
          foregroundColor: Colors.blue,
         ),
        ],
       );
      }
   }
Yash Jha
  • 137
  • 5
  • 16

4 Answers4

1

You can use Event_Bus to pass data between Screen.

This is lib

https://pub.dev/packages/event_bus

Nguyễn Trung Hiếu
  • 2,004
  • 1
  • 10
  • 22
0

The problem is when you're poping, state of your previous page is not updated. So, return the result with selected items (from checkboxes) as a future while poping. Once you pop check whether you got any result on not and hence rebuild the ui with new state.

0

You may utilize the return value of push

// _SecondPageState
FloatingActionButton(
  onPressed: () async {
    Set saved = await Navigator.push<Set>(
      context,
      MaterialPageRoute(builder: (context) => FavoriteList()),
    );
    setState(() {
      // do something
    });
  },
),
LoL
  • 162
  • 1
  • 6
0

Navigator.push() has a returned value, and you can pass in what you want while calling Navigator.pop()

This is the main code you should notice:

in SecondPage class:

FloatingActionButton(
  onPressed: () async {
    final Set indices = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => FavoriteList(indices: _indices), // you may wanna passing in what you have checked.
      ),
    );

    if (indices != null) {
      // do what you want, like setState()
      setState(() {
        final List tempIndices = _indices;
        tempIndices.addAll(indices);
        _indices = tempIndices.toSet().toList();
      });
    }
  },
),

and in FavoriteList class:

floatingActionButton: FloatingActionButton(
  onPressed: () {
    Navigator.pop(context, _saved);
  },
),

And if you want to check the complete code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Navigator Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SecondPage(),
    );
  }
}

class SecondPage extends StatefulWidget {

  @override
  _SecondPageState createState() => _SecondPageState();

}

class _SecondPageState extends State<SecondPage> {

  List _indices = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 75.0),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Add Your Favorite Sites Here!',
              style: TextStyle(
                color: Colors.black,
                fontSize: 24.0,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _indices.length,
                itemBuilder: (context, index) {
                  return Center(
                    child: Text(
                      '${_indices[index]}',
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 24.0,
                      ),
                    ),
                  );
                },
              ),
            ),
            FloatingActionButton(
              onPressed: () async {
                final Set indices = await Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => FavoriteList(indices: _indices),
                  ),
                );

                if (indices != null) {
                  setState(() {
                    final List tempIndices = _indices;

                    tempIndices.addAll(indices);

                    _indices = tempIndices.toSet().toList();
                  });
                }
              },
              child: Icon(
                Icons.add,
                color: Colors.white,
              ),
              foregroundColor: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }

}

class FavoriteList extends StatefulWidget {

  FavoriteList({
    Key key,
    this.indices,
  }) : super(key: key);

  final List indices;

  @override
  _FavoriteListState createState() => _FavoriteListState();

}

class _FavoriteListState extends State<FavoriteList> {

  final Set _saved = Set();

  @override
  void initState() {
    super.initState();

    _saved.addAll(widget.indices);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add to Favorites!'),
        centerTitle: true,
        backgroundColor: Colors.red,
      ),
      body: SafeArea(
        child: ListView.builder(
          itemCount: 53,
          itemBuilder: (context, index) {
            return CheckboxListTile(
              activeColor: Colors.red,
              checkColor: Colors.white,
              value: _saved.contains(index),
              onChanged: (val) {
                setState(() {
                  if (val == true) {
                    _saved.add(index);
                  } else {
                    _saved.remove(index);
                  }
                });
              },
              title: Row(
                children: <Widget>[
                  Text('$index'),
                ],
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        foregroundColor: Colors.red,
        child: Icon(Icons.check),
        onPressed: () {
          Navigator.pop(context, _saved);
        },
      ),
    );
  }

}

Sailendra
  • 1,318
  • 14
  • 29
halface_sun
  • 369
  • 3
  • 12