小编典典

扑setState到另一个类?

flutter

我有一个根类RootPageStatefulWidget它始终在视野中。我想改变bodyRootPage是通过控制RootPage's currentPage Widget从不同的类,如我的FeedPage类和其他类,我做什么呢?

范例程式码

import 'package:flutter/material.dart';

class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  FeedPage feedPage;

  Widget currentPage;

  @override
  void initState() {
    super.initState();
    feedPage = FeedPage();

    currentPage = feedPage;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //Current page to be changed from other classes too?
      body: currentPage
    );
  }
}



class FeedPage extends StatefulWidget {
  @override
  _feedPageState createState() => new _feedPageState();
}
class _feedPageState extends State<FeedPage> {

  @override
  Widget build(BuildContext context) {
    return new FlatButton(
      onPressed: () {
        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'),
    );
  }
}

我敢肯定有一个明显的答案,但是我似乎无法弄清楚如何有效地做到这一点,因此可以很容易地集成将来的类并使Root始终处于可见状态。


阅读 288

收藏
2020-08-13

共1个答案

小编典典

您可以使用 回调函数 来实现此目的。请参考下面的代码。

import 'package:flutter/material.dart';

class RootPage extends StatefulWidget {
  @override
  _RootPageState createState() => new _RootPageState();
}
class _RootPageState extends State<RootPage> {
  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<FeedPage> {

  @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'),
    );
  }
}
2020-08-13