Flutter: BottomNavigationBar rebuilds Page on change of tab

后端 未结 5 2009
小蘑菇
小蘑菇 2020-12-13 03:50

I have a problem with my BottomNavigationBar in Flutter. I want to keep my page alive if I change the tabs.

here my implementation

BottomNavigation

5条回答
  •  误落风尘
    2020-12-13 04:33

    I'm not sure but CupertinoTabBar would help.
    If you don't want it, this video would be great url.

    import 'dart:async';
    import 'dart:io';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
    
    class HomeScreen extends StatefulWidget {
      @override
      _HomeScreenState createState() => new _HomeScreenState();
    }
    
    class _HomeScreenState extends State {
      final List pages = [
        new Page1(),
        new Page2(),
        new Page3(),
        new Page4(),
      ];
    
      int currentIndex = 0;
    
      @override
      Widget build(BuildContext context) {
        return new WillPopScope(
          onWillPop: () async {
            await Future.value(true);
          },
          child: new CupertinoTabScaffold(
            tabBar: new CupertinoTabBar(
              iconSize: 35.0,
              onTap: (index) {
                setState(() => currentIndex = index);
              },
              activeColor: currentIndex == 0 ? Colors.white : Colors.black,
              inactiveColor: currentIndex == 0 ? Colors.green : Colors.grey,
              backgroundColor: currentIndex == 0 ? Colors.black : Colors.white,
              currentIndex: currentIndex,
              items: const [
                BottomNavigationBarItem(
                  icon: Icon(Icons.looks_one),
                  title: Text(''),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.looks_two),
                  title: Text(''),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.looks_3),
                  title: Text(''),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.looks_4),
                  title: Text(''),
                ),
              ],
            ),
            tabBuilder: (BuildContext context, int index) {
              return new DefaultTextStyle(
                style: const TextStyle(
                  fontFamily: '.SF UI Text',
                  fontSize: 17.0,
                  color: CupertinoColors.black,
                ),
                child: new CupertinoTabView(
                  routes: {
                    '/Page1': (BuildContext context) => new Page1(),
                    '/Page2': (BuildContext context) => new Page2(),
                    '/Page3': (BuildContext context) => new Page3(),
                    '/Page4': (BuildContext context) => new Page4(),
                  },
                  builder: (BuildContext context) {
                    return pages[currentIndex];
                  },
                ),
              );
            },
          ),
        );
      }
    }
    
    class Page1 extends StatefulWidget {
      @override
      _Page1State createState() => _Page1State();
    }
    
    class _Page1State extends State {
    
      String title;
    
     @override
      void initState() {
        title = 'Page1';
        super.initState();
      }
       @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
              title: new Text(title),
              leading: new IconButton(
                icon: new Icon(Icons.text_fields),
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) => Page13()));
                },
              )),
          body: new Center(
            child: new Text(title),
          ),
        );
      }
    }
    
    class Page2 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
            appBar: new AppBar(
                title: new Text('Page2'),
                leading: new IconButton(
                  icon: new Icon(Icons.airline_seat_flat_angled),
                  onPressed: () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) => Page12()));
                  },
                )),
            body: new Center(
              child: Column(
                children: [
                  CupertinoSlider(
                          value: 25.0,
                          min: 0.0,
                          max: 100.0,
                          onChanged: (double value) {
                            print(value);
                          }
                        ),
                ],
              ),
            ),
        );
      }
    }
    
    class Page3 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Page3'),
          ),
          body: new Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                new RaisedButton(
                    child: new Text('Cupertino'),
                    textColor: Colors.white,
                    color: Colors.red,
                    onPressed: () {
                      List list = List.generate(10, (int i) => i + 1);    
                      list.shuffle();
                      var subList = (list.sublist(0, 5));
                      print(subList);
                      subList.forEach((li) => list.remove(li));
                      print(list);
                    }
                ),
                new SizedBox(height: 30.0),
                new RaisedButton(
                    child: new Text('Android'),
                    textColor: Colors.white,
                    color: Colors.lightBlue,
                    onPressed: () {
                      var mes = 'message';
                      var messa = 'メッセージ';
                      var input = 'You have a new message';
                      if (input.contains(messa) || input.contains(mes)) {
                        print('object');
                      } else {
                        print('none');
                      }
                    }
                ),
              ],
            ),
          ),
        );
      }
    }
    
    class Page4 extends StatelessWidget {
      static List ints = [1, 2, 3, 4, 5];
    
      static _abc() {
        print(ints.last);
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Page4'),
          ),
          body: new Center(
              child: new RaisedButton(
            child: new Text('Static', style: new TextStyle(color: Colors.white)),
            color: Colors.lightBlue,
            onPressed: _abc,
          )),
        );
      }
    }
    
    class Page12 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Page12'),
            actions: [
              new FlatButton(
                child: new Text('GO'),
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) => Page13()));
                },
              )
            ],
          ),
          body: new Center(
              child: new RaisedButton(
            child: new Text('Swiper', style: new TextStyle(color: Colors.white)),
            color: Colors.redAccent,
            onPressed: () {},
          )),
        );
      }
    }
    
    class Page13 extends StatefulWidget {
      @override
      _Page13State createState() => _Page13State();
    }
    
    class _Page13State extends State with SingleTickerProviderStateMixin {
     final List _productLists = Platform.isAndroid
          ? [
              'android.test.purchased',
              'point_1000',
              '5000_point',
              'android.test.canceled',
            ]
          : ['com.cooni.point1000', 'com.cooni.point5000'];
    
      String _platformVersion = 'Unknown';
      List _items = [];
      List _purchases = [];
    
      @override
      void initState() {
        super.initState();
        initPlatformState();
      }
    
      Future initPlatformState() async {
        String platformVersion;
        try {
          platformVersion = await FlutterInappPurchase.platformVersion;
        } on PlatformException {
          platformVersion = 'Failed to get platform version.';
        }
    
        var result = await FlutterInappPurchase.initConnection;
        print('result: $result');
    
        if (!mounted) return;
    
        setState(() {
          _platformVersion = platformVersion;
        });
    
        // refresh items for android
        String msg = await FlutterInappPurchase.consumeAllItems;
        print('consumeAllItems: $msg');
      }
    
      Future _buyProduct(IAPItem item) async {
        try {
          PurchasedItem purchased = await FlutterInappPurchase.buyProduct(item.productId);
          print('purchased: ${purchased.toString()}');
        } catch (error) {
          print('$error');
        }
      }
    
      Future _getProduct() async {
        List items = await FlutterInappPurchase.getProducts(_productLists);
        print(items);
        for (var item in items) {
          print('${item.toString()}');
          this._items.add(item);
        }
    
        setState(() {
          this._items = items;
          this._purchases = [];
        });
      }
    
      Future _getPurchases() async {
        List items = await FlutterInappPurchase.getAvailablePurchases();
        for (var item in items) {
          print('${item.toString()}');
          this._purchases.add(item);
        }
    
        setState(() {
          this._items = [];
          this._purchases = items;
        });
      }
    
      Future _getPurchaseHistory() async {
        List items = await FlutterInappPurchase.getPurchaseHistory();
        for (var item in items) {
          print('${item.toString()}');
          this._purchases.add(item);
        }
    
        setState(() {
          this._items = [];
          this._purchases = items;
        });
      }
    
      List _renderInApps() {
        List widgets = this
            ._items
            .map((item) => Container(
                  margin: EdgeInsets.symmetric(vertical: 10.0),
                  child: Container(
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.only(bottom: 5.0),
                          child: Text(
                            item.toString(),
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        FlatButton(
                          color: Colors.orange,
                          onPressed: () {
                            print("---------- Buy Item Button Pressed");
                            this._buyProduct(item);
                          },
                          child: Row(
                            children: [
                              Expanded(
                                child: Container(
                                  height: 48.0,
                                  alignment: Alignment(-1.0, 0.0),
                                  child: Text('Buy Item'),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ))
            .toList();
        return widgets;
      }
    
      List _renderPurchases() {
        List widgets = this
            ._purchases
            .map((item) => Container(
                  margin: EdgeInsets.symmetric(vertical: 10.0),
                  child: Container(
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.only(bottom: 5.0),
                          child: Text(
                            item.toString(),
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ))
            .toList();
        return widgets;
      }
    
      @override
      Widget build(BuildContext context) {
        double screenWidth = MediaQuery.of(context).size.width-20;
        double buttonWidth=(screenWidth/3)-20;
    
        return new Scaffold(
          appBar: new AppBar(),
          body: Container(
          padding: EdgeInsets.all(10.0),
          child: ListView(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    child: Text(
                      'Running on: $_platformVersion\n',
                      style: TextStyle(fontSize: 18.0),
                    ),
                  ),
                  Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Container(
                            width: buttonWidth,
                            height: 60.0,
                            margin: EdgeInsets.all(7.0),
                            child: FlatButton(
                              color: Colors.amber,
                              padding: EdgeInsets.all(0.0),
                              onPressed: () async {
                                print("---------- Connect Billing Button Pressed");
                                await FlutterInappPurchase.initConnection;
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 20.0),
                                alignment: Alignment(0.0, 0.0),
                                child: Text(
                                  'Connect Billing',
                                  style: TextStyle(
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          Container(
                            width: buttonWidth,
                            height: 60.0,
                            margin: EdgeInsets.all(7.0),
                            child: FlatButton(
                              color: Colors.amber,
                              padding: EdgeInsets.all(0.0),
                              onPressed: () async {
                                print("---------- End Connection Button Pressed");
                                await FlutterInappPurchase.endConnection;
                                setState(() {
                                  this._items = [];
                                  this._purchases = [];
                                });
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 20.0),
                                alignment: Alignment(0.0, 0.0),
                                child: Text(
                                  'End Connection',
                                  style: TextStyle(
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Container(
                                width: buttonWidth,
                                height: 60.0,
                                margin: EdgeInsets.all(7.0),
                                child: FlatButton(
                                  color: Colors.green,
                                  padding: EdgeInsets.all(0.0),
                                  onPressed: () {
                                    print("---------- Get Items Button Pressed");
                                    this._getProduct();
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(horizontal: 20.0),
                                    alignment: Alignment(0.0, 0.0),
                                    child: Text(
                                      'Get Items',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ),
                                )),
                            Container(
                                width: buttonWidth,
                                height: 60.0,
                                margin: EdgeInsets.all(7.0),
                                child: FlatButton(
                                  color: Colors.green,
                                  padding: EdgeInsets.all(0.0),
                                  onPressed: () {
                                    print(
                                        "---------- Get Purchases Button Pressed");
                                    this._getPurchases();
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(horizontal: 20.0),
                                    alignment: Alignment(0.0, 0.0),
                                    child: Text(
                                      'Get Purchases',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ),
                                )),
                            Container(
                                width: buttonWidth,
                                height: 60.0,
                                margin: EdgeInsets.all(7.0),
                                child: FlatButton(
                                  color: Colors.green,
                                  padding: EdgeInsets.all(0.0),
                                  onPressed: () {
                                    print(
                                        "---------- Get Purchase History Button Pressed");
                                    this._getPurchaseHistory();
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(horizontal: 20.0),
                                    alignment: Alignment(0.0, 0.0),
                                    child: Text(
                                      'Get Purchase History',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ),
                                )),
                          ]),
                    ],
                  ),
                  Column(
                    children: this._renderInApps(),
                  ),
                  Column(
                    children: this._renderPurchases(),
                  ),
                ],
              ),
            ],
          ),
        ),
        );
      }
    }
    

提交回复
热议问题