flutter 如何维护抽屉子控件的状态

nx7onnlm  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(134)

我有一个有状态的小部件Counter,它有一个按钮和一个计数器,计数器记录按钮被按下的次数。这个小部件在抽屉里。当我再次关闭和打开抽屉时,计数器被重置。我如何使计数器在关闭和打开抽屉时不被重置?
代码如下:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        drawer: Drawer(
          child: Counter(),
        ),
        appBar: AppBar(),
        body: Container(),
      ),
    );
  }
}

class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(_count.toString()),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _count = _count + 1;
            });
          },
          child: Text('Increment Counter'),
        )
      ],
    );
  }
}
dldeef67

dldeef671#

要保持Drawer()中变量的状态,真正的解决方案是使用状态管理库。
但是,您可以做的是创建一个 global 变量,并将其沿树向下传递到Drawer()

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  var counter = 0;
  MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(

        drawer: Drawer(
          child: Counter(counter: counter,),
        ),
        appBar: AppBar(),
        body: Container(),
      ),
    );
  }
}


class Counter extends StatefulWidget {
  int counter;
  Counter({required this.counter,super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(widget.counter.toString()),
        ElevatedButton(
          onPressed: () {
            setState(() {
              widget.counter = widget.counter + 1;
            });
          },
          child: Text('Increment Counter'),
        )
      ],
    );
  }
}

相关问题