dart 如何将flutter Page(Widget)重置为初始状态(说明应用程序首次构建时的状态)

yduiuuwa  于 2023-06-03  发布在  Flutter
关注(0)|答案(7)|浏览(228)

假设我在页面上有一些滑块和开关,我更改它们的状态并修改它们,我知道我们执行setState来显示小部件树的更改状态并重建它,但我想知道是否有一种方法可以撤消所有这些更改并返回到初始状态(应用程序首次构建时的状态)?我不想调用一个自定义函数,手动将变量重置为初始值。也不应该删除和添加回路由(因为它会显示过渡)

bzzcjhmw

bzzcjhmw1#

如果你想打破常规

简答:

使用以下任何一项:

Navigator.pushReplacementNamed(context, '/currentRoute');
Navigator.popAndPushNamed(context, '/currentRoute');

长回答:

void main() => runApp(MaterialApp(home: DummyWidget()));

class DummyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) => HomePage();
}

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

class _HomePageState extends State<HomePage> {
  bool _enabled = false; // For Switch
  double _value = 0; // For Slider

  // This is the trick!
  void _reset() {
    Navigator.pushReplacement(
      context,
      PageRouteBuilder(
        transitionDuration: Duration.zero,
        pageBuilder: (_, __, ___) => DummyWidget(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Switch(
            value: _enabled,
            onChanged: (newValue) => setState(() => _enabled = newValue),
          ),
          Slider(
            value: _value,
            onChanged: (newValue) => setState(() => _value = newValue),
          ),
          TextButton(
            onPressed: _reset,
            child: Text('RESET'),
          ),
        ],
      ),
    );
  }
}

更好的方法可能是使用密钥。这里是key approach

0h4hbjxa

0h4hbjxa2#

一个简单的技巧是用同一条路线弹出和推。像这样:

Navigator.popAndPushNamed(context, "same_route");
pb3s4cty

pb3s4cty3#

截图:

使用key更改状态。

import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomePage()));

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

class _HomePageState extends State<HomePage> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: KeyedSubtree(
        key: ValueKey<int>(_count),
        child: Column(
          children: [
            MainPage(),
            ElevatedButton(
              onPressed: () => setState(() => ++_count),
              child: Text('RESET'),
            )
          ],
        ),
      ),
    );
  }
}

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  bool _enabled = false; // For Switch
  double _value = 0; // For Slider.

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          value: _enabled,
          onChanged: (newValue) => setState(() => _enabled = newValue),
        ),
        Slider(
          value: _value,
          onChanged: (newValue) => setState(() => _value = newValue),
        ),
      ],
    );
  }
}
slhcrj9b

slhcrj9b4#

这里是许多重置到初始数据的方法中的一种

import 'package:flutter/material.dart';

List<String> initialData = ['First', 'Second', 'Third'];

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: Example(),
    );
  }
}

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  List<String> items = [];

  @override
  void initState() {
    fillInitialData();
    super.initState();
  }

  fillInitialData() {
    items.addAll(initialData);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Example')),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) {
                return Card(
                  child: Padding(
                    padding: EdgeInsets.all(16.0),
                    child: Text(items[index]),
                  ),
                );
              },
            ),
          ),
          Row(
            children: <Widget>[
              FlatButton(
                onPressed: () {
                  setState(() {
                    items.add('A new item');
                  });
                },
                child: Text('Add an item'),
              ),
              FlatButton(
                onPressed: () {
                  setState(() {
                    items.clear();
                    fillInitialData();
                  });
                },
                child: Text('Reset'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
6yt4nkrj

6yt4nkrj5#

截图:

完整编码:

void main() {
  runApp(
    MaterialApp(
      // Passing initial values
      home: HomePage(enabled: false, value: 0),
    ),
  );
}

class HomePage extends StatefulWidget {
  final bool enabled;
  final double value;

  HomePage({this.enabled = false, this.value = 0});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _initialEnabled, _enabled; // For Switches
  double _initialValue, _value; // For Sliders

  @override
  void initState() {
    super.initState();

    // Assign them once (initial data)
    _initialEnabled ??= widget.enabled;
    _initialValue ??= widget.value;

    // These values can be changed by respective widgets
    _enabled = _initialEnabled;
    _value = _initialValue;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            Switch(
              value: _enabled,
              onChanged: (value) => setState(() => _enabled = value),
            ),
            Slider(
              value: _value,
              onChanged: (value) => setState(() => _value = value),
            ),
            RaisedButton(
              onPressed: () {
                setState(() {
                  // Resetting the values to initial ones which were passed
                  _enabled = _initialEnabled;
                  _value = _initialValue;
                });
              },
              child: Text('RESET'),
            ),
          ],
        ),
      ),
    );
  }
}
oymdgrw7

oymdgrw76#

在这种情况下,有几种古老的设计模式可能会有用。有一个重置选项很酷,但更酷的是 * 撤消 *。
通过以下教程了解如何在Flutter中实现 CommandMemento 模式:Command| Memento

vd8tlhqk

vd8tlhqk7#

您可以调用YourStateClass.initState()来恢复其初始化状态。
还要确保在构造状态时,要初始化void initState()函数中的所有变量。
例如

class FooState extends State<Foo> { 
    int someVariable;

    @override
    void initState() {
        someVariable = 0;
    }
}

您需要在initState()函数中为所有变量分配一个值,以便使其工作。
有关更多信息,请查看以下文档:https://api.flutter.dev/flutter/widgets/State/initState.html

相关问题