简体   繁体   中英

Update the state of navigation bar item in flutter

I have Navigation page contain navigation bar, one of these items it's friend request and I want show number of friend request, I do that, but I want update the number of friend request of item when the number increasing or decreasing in navigation page.

I'm passing the values of notifications below, so when I try to add a new friend request the notification numbers not change but when I closed app and reopen again the friend requests updated.

body: Stack(
            children: <Widget>[
              IndexedStack(
                children: <Widget>[
                  FriendRequestes(),
                  ChatListScreen(),
                  HomePage),
                  Tasks(),
                  Projects()
                ],
                index: _selectedItem,
              )


// Streambuilder to update the number of friend request from firestore
StreamBuilder(
                  stream: _firestore
                      .collection(USERS_COLLECTION)
                      .where(UID_FIELD, isEqualTo: widget.me.uid)
                      .limit(1)
                      .snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    const Text('Loading...');
                  } else {
                    return ListView.builder(
                        physics:
                        NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        scrollDirection:
                        Axis.vertical,
                        itemCount: snapshot
                            .data.documents.length,
                        itemBuilder:
                            (context, index) {
                 
                          DocumentSnapshot userData = snapshot.data.documents[index];

                          List<String> requested = <String>[];

                          if(userData.data[REQUESTED_FIELD] != null)
                          {
                            List.from(userData.data[REQUESTED_FIELD]).forEach((element){
                              requested.add(element);
                            });
                          }

                          widget.me = User(
                            arrayRequested: requested,
                          );
                          rebuild(widget.me);

                          return Container(width: 0.0,height: 0.0,);
                        });
                  }
                  return Container(
                    height: 0.0,
                    width: 0.0,
                  );
                },
              ),

bottomNavigationBar: CustomBottomNavigationBar(
            onChange: (val) {
              setState(() {
                _selectedItem = val;
              });
            },
            defaultSelectedIndex: 2,
            width: width,
            lang: widget.myAppLang,
            iconList: [
              "assets/icon/icon_friendReq.png",
              "assets/icon/icon_chats.png",
              "assets/icon/icon_home.png",
              "assets/icon/icon_tasks.png",
              "assets/icon/icon_projects.png",
            ],
            textList: [
              "Profile",
              "Chats",
              "Home",
              "Tasks",
              "Projects",
            ],
            // here I'm passing notification number
            notiList: [widget.me.arrayRequested.length, 0, 0, 0, 0],
          ),



   // to update the state of number of friend requests from firestore 

rebuild(User user){
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        widget.me = user;
      });
    });
  }


 // Navigation Bar
class CustomBottomNavigationBar extends StatefulWidget {
  final int defaultSelectedIndex;
  final double width;
  String lang;
  final Function(int) onChange;
  final List<String> iconList;
  final List<String> textList;
  final List<int> notiList;


  CustomBottomNavigationBar(
      {this.defaultSelectedIndex = 0,
      @required this.iconList,
      @required this.textList,
      @required this.notiList,
      @required this.onChange,
      @required this.width,
      @required this.lang,
      });

  @override
  _CustomBottomNavigationBarState createState() =>
      _CustomBottomNavigationBarState();
}

class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
  int _selectedIndex = 0;
  double _width;
  String _lang;
  List<String> _iconList = [];
  List<String> _textList = [];
  List<int> _notiList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();



    _selectedIndex = widget.defaultSelectedIndex;
    _iconList = widget.iconList;
    _textList = widget.textList;
    _notiList = widget.notiList;
    _width = widget.width;
    _lang = widget.lang;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _navBarItemList = [];

    for (var i = 0; i < _iconList.length; i++) {
      _navBarItemList
          .add(buildNavBarItem(_width, _lang, _iconList[i], _textList[i], _notiList[i], i));
    }

    return Row(
      children: _navBarItemList,
    );
  }

  Widget buildNavBarItem(
      double width, String lang, String icon, String text, int n, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widget.onChange(index);
          _selectedIndex = index;
          n = n;
        });

      },
      child: Stack(
        children: [
          Container(
            height: width * 0.18,
            width: MediaQuery.of(context).size.width / _iconList.length,
            decoration: index == _selectedIndex
                ? BoxDecoration(
              color: GlobalUniversal.blackForIcons.withOpacity(0.08),
              border: Border(
                bottom: BorderSide(width: 4, color: GlobalUniversal.purple),
              ),
              /*
            gradient: LinearGradient(colors: [
              Colors.green.withOpacity(0.3),
              Colors.green.withOpacity(0.015),
            ], begin: Alignment.bottomCenter, end: Alignment.topCenter)
             */
              // color: index == _selectedItemIndex ? Colors.green : Colors.white,
            )
                : BoxDecoration(),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageIcon(
                  AssetImage(icon),
                  color: index == _selectedIndex
                      ? GlobalUniversal.blackForIcons
                      : Colors.grey,
                ),
                SizedBox(
                  height: 3.0,
                ),
                Text(
                  text,
                  textScaleFactor: 1.0,
                  style: TextStyle(
                      color: index == _selectedIndex
                          ? GlobalUniversal.blackForIcons
                          : Colors.grey,
                      fontFamily: lang != LANG_EN ? FONT_AR : FONT_EN),
                ),
              ],
            ),
          ),
          Visibility(
            visible: n != 0 && n != null,
            child: Container(
              margin: EdgeInsets.all(5.0),
              padding: EdgeInsets.all(5.0),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xffc32c37),
              ),
              child: Text(
                n.toString(),
                textScaleFactor: 1.0,
                style: TextStyle(
                    color: GlobalUniversal.whiteBG,
                    fontSize: 10.0),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

The state is not updating because the number of the request value is not in a StreamBuilder which means it is not asynchronous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM