Flutter:setState未更新自定义构建的小部件

时间:2020-08-08 01:24:29

标签: flutter dart

我构建了一个自定义计时器小部件,并通过main.dart文件进行调用。我的计时器窗口小部件实质上接受了一个参数totalDuration,并使用该参数开始运行计时器。在main.dart文件中,我创建了一个名为counter的变量,并将其作为值传递给totalDuration。到这里为止一切正常。现在,当我创建一个按钮时,单击该按钮会增加计数器变量并调用setState方法,我的计数器变量正在增加,但未重建窗口小部件。为什么会这样,我该如何解决这个问题?作为参考,我在这里附加了我的主文件和计时器文件中的代码。

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app_test_counter/timer.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 60;

  void _incrementCounter() {
    setState(() {
      print(_counter);
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Expanded(
              child: Timer(
                totalDuration: _counter,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

timer.dart

import 'dart:ui';

import 'package:flutter/material.dart';

class Timer extends StatefulWidget {
  final int totalDuration;
  const Timer({Key key, this.totalDuration}) : super(key: key);

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

class _Timer extends State<Timer> with TickerProviderStateMixin {
  double _progress = 0.0;
  bool _reversed = true;
  bool _stopped = false;
  Duration duration;

  Animation<double> animation;
  AnimationController controller;

  String get _timeRemaining {
    if (controller.lastElapsedDuration != null) {
      duration = _reversed
          ? controller.duration - controller.lastElapsedDuration
          : controller.lastElapsedDuration + Duration(seconds: 1);
    }
    return '${(duration.inHours).toString().padLeft(2, '0')}:${(duration.inMinutes % 60).toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

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

    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: widget.totalDuration),
    );

    animation = Tween(begin: 1.0, end: 0.0).animate(controller)
      ..addListener(() {
        setState(() {
          _progress = animation.value;
        });
      });

    controller.forward();
  }

  @override
  void dispose() {
    controller.dispose();
    _stopped = !_stopped;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _reversed = !_reversed,
      child: Scaffold(
        body: CustomPaint(
          painter:
              ShapePainter(progress: _progress, timeRemaining: _timeRemaining),
          child: Container(),
        ),
      ),
    );
  }
}

class ShapePainter extends CustomPainter {
  double progress;
  String timeRemaining;

  ShapePainter({this.progress, this.timeRemaining});

  @override
  void paint(Canvas canvas, Size size) {
    final rectBounds = Rect.fromLTRB(0, 0, size.width, size.height);
    final rectPaint = Paint()
      ..strokeWidth = 1
      ..style = PaintingStyle.fill
      ..color = Colors.orange;
    canvas.drawRRect(
      RRect.fromRectAndRadius(rectBounds, Radius.circular(10)),
      rectPaint,
    );

    var paintProgressBar = Paint()
      ..color = Colors.white
      ..strokeWidth = 6
      ..strokeCap = StrokeCap.round;
    Offset progressStartingPoint = Offset(42, size.height - 60);
    Offset progressEndingPoint = Offset(size.width - 42, size.height - 60);
    canvas.drawLine(
        progressStartingPoint, progressEndingPoint, paintProgressBar);

    var paintDoneBar = Paint()
      ..color = Colors.deepOrange
      ..strokeWidth = 6
      ..strokeCap = StrokeCap.round;
    Offset doneStartingPoint = Offset(42, size.height - 60);
    Offset doneEndingPoint =
        Offset(((size.width - 84) * (1.0 - progress) + 42), size.height - 60);
    canvas.drawLine(doneStartingPoint, doneEndingPoint, paintDoneBar);

    final timerTextStyle = TextStyle(
      color: Colors.indigo,
      fontSize: 30,
    );
    final timerTextSpan = TextSpan(
      text: timeRemaining,
      style: timerTextStyle,
    );
    final timerTextPainter = TextPainter(
      text: timerTextSpan,
      textDirection: TextDirection.ltr,
    );
    timerTextPainter.layout(
      minWidth: 0,
      maxWidth: size.width,
    );
    final timerOffset = Offset(size.width / 2, size.height / 2 - 40);
    timerTextPainter.paint(canvas, timerOffset);

    final textStyle = TextStyle(
      color: Colors.black,
      fontSize: 30,
    );
    final textSpan = TextSpan(
      text: 'time left',
      style: textStyle,
    );
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(
      minWidth: 0,
      maxWidth: size.width,
    );
    final offset = Offset((size.width - 20) / 2, (size.height - 20) / 2);
    textPainter.paint(canvas, offset);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

1 个答案:

答案 0 :(得分:1)

一个快速的肮脏解决方法是将key添加到“计时器”小部件

Timer(
  key: UniqueKey(),
  totalDuration: _counter,
),

其他方法是在孩子的didUpdateWidget小部件中使用Timer()功能。 在该功能中,您可以进行更改。

@override
void didUpdateWidget(Timer oldWidget) {
  print("didUpdateWidget called");
  super.didUpdateWidget(oldWidget);
}

https://api.flutter.dev/flutter/widgets/State/didUpdateWidget.html