Анимация флаттера не работает с данными провайдера - PullRequest
0 голосов
/ 18 января 2020

Я сделал индикатор прогресса градиента, который работал нормально, пока я не хотел добавить анимацию. Мое приложение использует провайдера для хранения всего в классе ChangeNotifier. Я попытался добавить слушателя, чтобы оживить изменение. Когда данные меняются, я получаю:

════════ Exception caught by foundation library ════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while dispatching notifications for Tasks:
The getter 'owner' was called on null.
Receiver: null
Tried calling: owner

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      Provider.of (package:provider/src/provider.dart:213:15)
#2      _GradientProgressIndicatorState.didChangeDependencies.<anonymous closure> (package:todo/components/gradient_progress_indicator.dart:50:29)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:206:21)
#4      Category.createTask (package:todo/models/category.dart:35:8)
...
The Tasks sending notification was: Instance of 'Tasks'
════════════════════════════════════════════════════════════════════════════════════════════════════

Вот мой исходный код:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../models/tasks.dart';

class GradientProgressIndicator extends StatefulWidget {
  final Color inactiveColor;
  final Gradient gradient;

  GradientProgressIndicator({this.inactiveColor, this.gradient});

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

class _GradientProgressIndicatorState extends State<GradientProgressIndicator>
    with SingleTickerProviderStateMixin {
  double oldValue = 0;
  AnimationController controller;
  Animation animation;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500),
    );
    animation = Tween(
            begin: oldValue,
            end: Provider.of<Tasks>(context, listen: false)
                .currentCategory
                .taskPercentage)
        .animate(controller);
    oldValue = Provider.of<Tasks>(context, listen: false)
        .currentCategory
        .taskPercentage;
    controller.forward();
    controller.addListener(() {
      setState(() {});
    });
  }

  @override
  void didChangeDependencies() {
    Provider.of<Tasks>(context).addListener(() {
      animation = Tween(
              begin: oldValue,
              end: Provider.of<Tasks>(context, listen: false) //this is the line which the error mention
                  .currentCategory
                  .taskPercentage)
          .animate(controller);
      oldValue = Provider.of<Tasks>(context, listen: false)
          .currentCategory
          .taskPercentage;
      controller.forward();
    });
    super.didChangeDependencies();
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(5),
        ),
        color: widget.inactiveColor,
      ),
      height: 3,
      width: double.infinity,
      child: FractionallySizedBox(
        widthFactor: animation.value,
        alignment: Alignment.centerLeft,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(5),
            ),
            gradient: widget.gradient,
          ),
        ),
      ),
    );
  }
}

(Provider.of<Tasks>(context, listen: false).currentCategory.taskPercentage возвращает двойное значение от 0 до 1)
И вот что я получаю от трепетного доктора:

[✓] Flutter (Channel master, v1.13.7-pre.12, on Linux, locale en_GB.UTF-8)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Android Studio (version 3.5)
[✓] Connected device (1 available)

• No issues found!

Есть идеи, что является источником проблемы?

...