Losing widget state when switching pages in a Flutter PageView

前端 未结 3 2059
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 21:07

I have a series of stateful widgets in a PageView managed by a PageController. I am using pageController.jumpToPage(index) to switch pages. When switching pages

3条回答
  •  伪装坚强ぢ
    2020-12-23 21:51

    use with AutomaticKeepAliveClientMixin to your SubPage.

    then @override bool get wantKeepAlive => true; here is a sample

    import 'package:flutter/material.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      @override
      Widget build(BuildContext context) {
        return DefaultTabController(
          length: 4,
          child: new Scaffold(
            appBar: new AppBar(
              bottom: new TabBar(
                tabs: [
                  new Tab(icon: new Icon(Icons.directions_car)),
                  new Tab(icon: new Icon(Icons.directions_transit)),
                  new Tab(icon: new Icon(Icons.directions_bike)),
                  new Tab(
                    icon: new Icon(Icons.airplanemode_active),
                  )
                ],
              ),
            ),
            body: new TabBarView(children: [
              new OnePage(color: Colors.black,),
              new OnePage(color: Colors.green,),
              new OnePage(color: Colors.red,),
              new OnePage(color: Colors.blue,),
            ]),
          ),
        );
      }
    }
    
    class OnePage extends StatefulWidget {
      final Color color;
    
      const OnePage({Key key, this.color}) : super(key: key);
    
      @override
      _OnePageState createState() => new _OnePageState();
    }
    
    class _OnePageState extends State with AutomaticKeepAliveClientMixin {
      @override
      Widget build(BuildContext context) {
        super.build(context);
        return new SizedBox.expand(
          child: new ListView.builder(
            itemCount: 100,
            itemBuilder: (context, index) {
              return new Padding(
                padding: const EdgeInsets.all(10.0),
                child: new Text(
                  '$index',
                  style: new TextStyle(color: widget.color),
                ),
              );
            },
          ),
        );
      }
    
      @override
      bool get wantKeepAlive => true;
    }
    

提交回复
热议问题