BottomNavigationBar内部小部件的持久性

时间:2019-04-18 09:07:02

标签: dart flutter

当BottomNavigationBar的选项卡切换时,我希望我的应用程序保持子窗口小部件的状态。问题是,每当我更改标签时,小部件都会重建到初始状态。

我已经尝试过使用按键,但是我对按键应该如何操作没有完全的了解。我也按照How to persist tabs when using BottomNavigationBar?中所述对Offstage进行了尝试,但仍然无法正常工作。

这是“首页”,它是其他页面的中心:


  List<Widget> pages;
  Widget settingsPage;
  Widget chatPage;
  Widget searchPage;
  Widget favPage;
  Widget addOffer;

  Widget currentPage;

  //index describing currently selected tab
  int _index = 4;

  final PageStorageBucket bucket = PageStorageBucket();

  void selectedTab(int value) {
    setState(() {
      _index = value;
    });
  }

  @override
  void initState() {
    settingsPage = SettingsPage(key: PageStorageKey('Settings'));
    chatPage = Container(key: PageStorageKey('Chat'));
    searchPage = SearchPage(key: PageStorageKey('Search'));
    favPage = Container(key: PageStorageKey('Favourite'));
    addOffer = AddOffer(key: UniqueKey());
    pages = [settingsPage, chatPage, searchPage, favPage, addOffer];
    currentPage = pages[_index];
    super.initState();
  }

  PageStorageKey mykey = new PageStorageKey("testkey");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: PageStorage(
          bucket: bucket,
          child: currentPage,
//          key: mykey,
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          fixedColor: Theme.of(context).primaryColor,
          currentIndex: _index,
          onTap: (index) {
            setState(() {
              _index = index;
              currentPage = pages[index];
            });
          },
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text('Settings')),
            BottomNavigationBarItem(icon: Icon(Icons.chat), title: Text('Chat')),
            BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('Offers')),
            BottomNavigationBarItem(icon: Icon(Icons.favorite), title: Text('Favourite')),
            BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Add'))
          ]),
    );
  }

这是“ AddOffer”正文:

 final List<DropdownMenuItem> _cityMenuItem = [
    'Kraków',
    'Łódź',
    'Poznań',
    'Katowice',
    'Warszawa',
    'Gdańsk',
    'Tumulec',
    'Pędzichów',
    'Kąty Opolskie'
  ]
      .map<DropdownMenuItem>((city) => DropdownMenuItem<String>(
            child: Text(city),
            value: city,
          ))
      .toList();

  final List<DropdownMenuItem> _roomMenuItem = [
    'Łazienka',
    'Toalteta',
    'Kuchnia',
    'Salon z Aneksem kuchennym',
    'Przechodni',
    'Nieprzechodni',
    'Inne'
  ]
      .map<DropdownMenuItem>((room) => DropdownMenuItem<String>(
            child: Text(room),
            value: room,
          ))
      .toList();

  String _citySelected;
  String _roomSelected;

  String _streetName;
  String _streetNumber;
  double _deposit;
  double _totalPrice;

  List<RoomCard> _rooms = []; // = [Container()];

  List<RoomImages> _roomImages = [];

  @override
  void initState() {
    //default state of dropdown menus
    _citySelected = _cityMenuItem[0].value;
    _roomSelected = _roomMenuItem[0].value;
    debugPrint(widget.key.toString());

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    /// ListView used in case content will extend through screen
    return ListView(
      padding: EdgeInsets.all(12),
      children: <Widget>[
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          key: PageStorageKey('asda'),
          children: [
            <Widget>[
              Text('Dodaj ofertę', style: TextStyle(fontSize: 18)),

              ///            Choose city
              DropdownButton(
                  isExpanded: true,
                  hint: Text('Wybierz miasto'),
                  items: _cityMenuItem,
                  value: _citySelected,
                  onChanged: (newValue) {
                    setState(() => _citySelected = newValue
//                    debugPrint(newValue);
                        );
                  }),

              ///           Add Street name and number
              Row(children: <Widget>[
                Flexible(
                    flex: 4,
                    child: TextFormField(
                      key: PageStorageKey('$_streetName'),
                      initialValue: _streetName,
                      scrollPadding: EdgeInsets.all(202),
                      textCapitalization: TextCapitalization.sentences,
                      onSaved: null,
                      decoration: InputDecoration(
                        border: UnderlineInputBorder(),
                        labelText: 'Ulica *',
                        prefixText: 'ul. ',
                      ),
                    )),
                SizedBox(width: 12),
                Flexible(
                    child: TextFormField(
                  key: PageStorageKey('$widget.'),
                  decoration: InputDecoration(
                    border: UnderlineInputBorder(),
                    filled: false,
                    labelText: 'Numer',
                  ),
                  keyboardType: TextInputType.numberWithOptions(decimal: false, signed: false),
                ))
              ]),
              SizedBox(height: 16),

              ///            Add room to offer
              Row(
                children: <Widget>[
                  Flexible(
                    child: DropdownButton(
                      isExpanded: true,
                      hint: Text('Dodaj pokój'),
                      items: _roomMenuItem,
                      value: _roomSelected,
                      onChanged: (newValue) {
                        setState(() => _roomSelected = newValue);
                      },
                    ),
                  ),
                  SizedBox(width: 16),
                  RaisedButton(
                    onPressed: () {
                      setState(() {
                        _roomImages.add(RoomImages(
                          roomName: _roomSelected,
                          key: UniqueKey(),
                        ));
                      });
                    },
                    child: Icon(Icons.add),
                  )
                ],
              ),
              SizedBox(height: 16),
            ],

            ///            Display rooms in offer
            _roomImages,

            ///
            <Widget>[
              SizedBox(height: 8),

              ///              Enter price
              Row(
                children: <Widget>[
                  Flexible(
                    child: TextFormField(
                      keyboardType: TextInputType.numberWithOptions(),
                      decoration: InputDecoration(
                        suffixText: 'PLN',
                        border: OutlineInputBorder(),
                        labelText: 'Kaucja *',
                      ),
                    ),
                  ),
                  SizedBox(width: 16),
                  Flexible(
                    child: TextFormField(
                      keyboardType: TextInputType.numberWithOptions(),
                      decoration: InputDecoration(
                          suffixText: 'PLN',
                          border: OutlineInputBorder(),
                          labelText: 'Całkowita cena *'),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8),

              ///              Create an offer
              RaisedButton(
                onPressed: () {},
                child: Text('Stwórz ofertę'),
              )
            ]
          ].expand<Widget>((f) => f).where((item) => item != null).toList(),
        ),
      ],
    );
  }

显示问题的GIF链接:https://gph.is/g/Z85pz14 我想使创建的条目持久化。

0 个答案:

没有答案