如何在Flutter中在不同的有状态小部件之间来回移动数据?

时间:2019-06-28 13:36:01

标签: flutter dart

第一个有状态小部件中有count个变量,我已将其传递给Setting class。并且,Setting class将其传递给SettingStateBuilder。然后,在increamenting的{​​{1}}()中更改其值。我希望更新后的值返回到SettingStateBuilder以进行进一步的工作。我该怎么办?

第一个有状态窗口小部件的创建如下:

HomePageBody

第二状态小部件的创建如下:

class HomePage extends StatefulWidget {
  @override
  HomePageBody createState() => HomePageBody();
}

class HomePageBody extends State<HomePage> {
   int count=0;
   @override
   Widget build(BuildContext context) {
       ...
       new Setting(count);
   }
}

1 个答案:

答案 0 :(得分:1)

您可以将Function属性添加到Settings小部件,当计数器增加时将调用该属性,并在创建小部件时传递该函数,以便在HomePage中进行更新柜台:

class HomePage extends StatefulWidget {
  @override
  HomePageBody createState() => HomePageBody();
}

class HomePageBody extends State<HomePage> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          MaterialButton(
            child: Text('Settings'),
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (BuildContext context) => Settings(
                        count,
                        (newCount) {
                          setState(
                            () {
                              count = newCount;
                            },
                          );
                        },
                      ),
                ),
              );
            },
          )
        ],
      ),
      body: Center(
        child: Text('$count'),
      ),
    );
  }
}

class Settings extends StatefulWidget {
  final int count;
  final Function(int) onCounterChanged;

  Settings(this.count, onCounterChanged);

  @override
  SettingsStateBuilder createState() => SettingsStateBuilder(count);
}

class SettingsStateBuilder extends State<Settings> {
  int count;
  SettingsStateBuilder(this.count);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('$count'),
            MaterialButton(
              child: Text('Increment'),
              onPressed: () => setState(
                    () {
                      increment();
                    },
                  ),
            ),
          ],
        ),
      ),
    );
  }

  increment() {
    count += 1;
    widget.onCounterChanged(count);

  }
}

如果您要处理更复杂的用例,建议您阅读有关如何在Flutter中进行状态管理的内容,

https://flutter.dev/docs/development/data-and-backend/state-mgmt/intro https://flutter.dev/docs/development/data-and-backend/state-mgmt/options