Flutter setState to another class?

后端 未结 4 1177
日久生厌
日久生厌 2020-11-27 20:54

I have a root class RootPage which is a StatefulWidget which is always in view. I would like to change the body in RootPage

4条回答
  •  广开言路
    2020-11-27 21:44

    You can use callbacks functions to achieve this. Please refer to the below code.

    import 'package:flutter/material.dart';
    
    class RootPage extends StatefulWidget {
      @override
      _RootPageState createState() => new _RootPageState();
    }
    class _RootPageState extends State {
      FeedPage feedPage;
    
      Widget currentPage;
    
      @override
      void initState() {
        super.initState();
        feedPage = FeedPage(this.callback);
    
        currentPage = feedPage;
      }
    
      void callback(Widget nextPage) {
        setState(() {
          this.currentPage = nextPage;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          //Current page to be changed from other classes too?
            body: currentPage
        );
      }
    }
    
    
    
    class FeedPage extends StatefulWidget {
      Function callback;
    
      FeedPage(this.callback);
    
      @override
      _feedPageState createState() => new _feedPageState();
    }
    class _feedPageState extends State {
    
      @override
      Widget build(BuildContext context) {
        return new FlatButton(
          onPressed: () {
            this.widget.callback(new NextPage());
    //        setState(() {
    //          //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make
    //        });
          },
          child: new Text('Go to a new page but keep root, just replace this feed part'),
        );
      }
    }
    

    This is very similar to this problem and you could refer 3rd point in my answer.

提交回复
热议问题