Home > database >  Flutter: How to transfer variables when using BottomNavigationBar?
Flutter: How to transfer variables when using BottomNavigationBar?

Time:02-21

I have made a BottomNavigationBar with two BottomNavigationBarItem, which can lead to two different pages HomePage and PersonalPage by clicking. There is a variable named money in PersonalPage. I wondered that how to transfer money from PersonalPage to HomePage through BottomNavigationBar, or transfer money from PersonalPage to the controlling page, which contains a _pageList containing HomePage and PersonalPage. Here are the codes of controlling page:

class MainPageState extends State<MainPage> {
  var _currentIndex = 0;
  var i = 0;
  String _title = "首页";
  double _barHeight = 60;
  bool _primary = true;
  Color _color = Colors.blue;
  double _elevation = 10;
  var _pageList = [HomePage(), PersonalPage(money: money, key: Key('keyName'))];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
        centerTitle: true,
        elevation: _elevation,
        toolbarHeight: _barHeight,
        //primary: _primary,
        backgroundColor: _color,

      ),
      //body: this._pageList[this._currentIndex],
      body: IndexedStack(index: _currentIndex, children: _pageList),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(
              Icons.home,
              //color: _currentIndex == 0 ? Colors.blue : Colors.grey,
            ),
            label: "首页",
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.person,
              //color: _currentIndex == 2 ? Colors.blue : Colors.grey,
            ),
            label: "我的",
          )
        ],
        onTap: (value){
          setState(() {
            this._currentIndex = value.toInt();
            this.i = _currentIndex;
            switch(i){
              case 0: {
                _title = "首页";
                _barHeight = 60;
                _primary = true;
                _color = Colors.blue;
                _elevation = 10;
              } break;
              case 1: {
                _title = "我的";
                _barHeight = 10;
                _primary = false;
                _color = Colors.white70;
                _elevation = 0;
              } break;
            }
          });
        },
        type: BottomNavigationBarType.fixed,
      ),
    );
  }
}

As you can see, when creating PersonalPage, I will transfer the variable money to it. The problem is that how to transfer the changed money back.

Thanks for your help. This question maybe quite immature but it is my first Flutter project.

CodePudding user response:

You can refer it:

class _HomePage extends State<HomePage> {
 int curentIndex = 0;
 final GlobalKey<CurvedNavigationBarState> 
 _bottomNavigationKey = GlobalKey();
 @override
 Widget build(BuildContext context) {
 final Screen = [
  CourseScreen(),
  RequestScreen(),
  HistoryScreen(),
  NewsScreen(),
  ProfileScreen(),
];

return Scaffold(
    body: Screen[curentIndex],
    bottomNavigationBar: CurvedNavigationBar(
      key: _bottomNavigationKey,
      index: curentIndex,
      height: 60.0,
      items: const <Widget>[
        Icon(Icons.book, size: 30),
        Icon(Icons.request_page, size: 30),
        Icon(Icons.history_edu, size: 30),
        Icon(Icons.new_label_outlined, size: 30),
        Icon(Icons.account_box, size: 30),
      ],
      color: Colors.white,
      buttonBackgroundColor: Colors.white,
      backgroundColor: Colors.blueAccent,
      animationCurve: Curves.easeInOut,
      animationDuration: Duration(milliseconds: 600),
      onTap: (index) {
        setState(() {
          curentIndex = index;
        });
      },
      letIndexChange: (index) => true,
    ));
  }
 }

CodePudding user response:

You can use provider state manager for this purpose.

First create money model class:

class MoneyModel extends ChangeNotifier {
  double value = 00.0; /// This variable holds value of money
}

Then wrap your app with ChangeNotifierProvider:

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => MoneyModel(),
      child: MyApp(),
    ),
  );
}

Now MoneyModel (and it's value consequently) is accessible anywhere in your app. You can read (or change) it's value like this:

/// Read value
Provider.of<MoneyModel>(context, listen: false).value;
/// Change value
Provider.of<MoneyModel>(context).value = 12.99;
  • Related