Flutter 中的“脏”是什么?是什么导致了这种“脏”状态?

时间:2021-04-22 04:14:17

标签: flutter state-management getx flutter-getx

我正在尝试通过这个演示项目学习状态管理和依赖注入。我正在尝试演示在所有地方注入一些方法,就像我可能需要在我的程序中一样。我使用 GetX 是因为我喜欢在非小部件类中无需上下文即可执行此操作。

所以我的问题是下面最后一个类中的最后一个方法 summationReturns()。尝试使用带有 return 语句的方法并将它们添加在一起。我在两个地方称之为。在浮动按钮中,这工作正常,但在我的文本小部件中,我收到一个脏状态错误。

当其他一切正常时,为什么这不起作用?我认为这将是最后一个问题的推论,什么是脏状态?似乎是两个问题,但我想它们是同一个问题。

///
///
/// DEMO PROJECT WORKING OUT GETX
/// WORKOUT DEPENDANCY INJECTION AND STATE MANAGEMENT

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

void main() {
  runApp(GetMaterialApp(
    home: Home(),
    debugShowCheckedModeBanner: false,
  ));
}

class Home extends StatelessWidget {
  // Injection of dependancy
  final Controller controller = Get.put(Controller());
  final Observable observable = Get.put(Observable());
  final SimpleMath simpleMath = Get.put(SimpleMath());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GetX Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Get builders:'),
            GetBuilder<Controller>(builder: (controller) {
              return Text(controller.count.toString());
            }),
            GetBuilder<Controller>(builder: (controller) {
              return Text(controller.countList.toString());
            }),
            GetBuilder<Controller>(builder: (controller) {
              return Text(controller.returnCount().toString());
            }),
            GetBuilder<Controller>(builder: (controller) {
              return Text(controller.returnList().toString());
            }),
            SizedBox(height: 20.0),
            Text('Get observables:'),
            Obx(() => Text(observable.count.value.toString())),
            Obx(() => Text(observable.countList.value.toString())),
            Obx(() => Text(observable.returnCount().toString())),
            Obx(() => Text(observable.returnList().toString())),
            SizedBox(height: 20.0),
            Text('Get from other class:'),
            GetBuilder<SimpleMath>(builder: (simpleMath) {
              return Text('Variable summation: ' + simpleMath.summationVariables().toString());
            }),
            GetBuilder<SimpleMath>(builder: (simpleMath) {
              return Text(simpleMath.summationReturns().toString());
            }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          controller.crunch();
          observable.crunch();
          simpleMath.summationVariables();
          simpleMath.summationReturns();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Controller extends GetxController {
  int count = 0;
  List<int> countList = [];

  void crunch() {
    count += 1;
    countList.add(count);
    update();
  }

  int returnCount() {
    return count;
  }

  List<int> returnList() {
    return countList;
  }
}

class Observable extends GetxController {
  RxInt count = 0.obs;
  Rx<RxList> countList = RxList().obs;

  void crunch() {
    count.value += 1;
    countList.value.add(count.value);
  }

  int returnCount() {
    return count.value;
  }

  List<dynamic> returnList() {
    return countList.value.toList();
  }
}

class SimpleMath extends GetxController {
  final Controller controller = Get.find<Controller>();
  final Observable observable = Get.find<Observable>();

  int summationVariables() {
    int sum = controller.count + observable.count.value;
    update();
    return sum;
  }

  int summationReturns() {
    int sum = controller.returnCount() + observable.returnCount();
    print('Summation of return values: ' + sum.toString());
    update();
    return sum;
  }
}

错误:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building GetBuilder<SimpleMath>(dirty, state:
GetBuilderState<SimpleMath>#4d62d):
setState() or markNeedsBuild() called during build.
This GetBuilder<SimpleMath> widget cannot be marked as needing to build because the framework is
already in the process of building widgets.  A widget can be marked as needing to be built during
the build phase only if one of its ancestors is currently building. This exception is allowed
because the framework builds parent widgets before children, which means a dirty descendant will
always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
  GetBuilder<SimpleMath>
The widget which was currently being built when the offending call was made was:
  GetBuilder<SimpleMath>

The relevant error-causing widget was:
  GetBuilder<SimpleMath>
  file:///Users/robertobuttazzoni/Documents/Flutter%20Tutorials/Flutter%20Learning/getx_basics/getx_basics/lib/main.dart:57:13

1 个答案:

答案 0 :(得分:1)

在构建过程中调用 update 是脏场景的一个例子。要解决您的问题,请不要在 update 内调用 GetBuilder

示例...

在家

GetBuilder<SimpleMath>(
    builder: (simpleMath) => Text('Variable summation: ' +
        simpleMath
            .summationVariables(shouldUpdate: false)
            .toString())),
GetBuilder<SimpleMath>(
    builder: (simpleMath) => Text(simpleMath
        .summationReturns(shouldUpdate: false)
        .toString())),

在简单数学中

int summationVariables({bool shouldUpdate = true}) {
  int sum = controller.count + observable.count.value;
  if (shouldUpdate) update();
  return sum;
}

int summationReturns({bool shouldUpdate = true}) {
  int sum = controller.returnCount() + observable.returnCount();
  print('Summation of return values: ' + sum.toString());
  if (shouldUpdate) update();
  return sum;
}
相关问题