首页 > 解决方案 > NotifyListeners 不会在颤动中重建小部件

问题描述

我正在构建一个应用程序,它的屏幕上有很多文本字段,您可以四处移动和自定义。我想通过单击位于单独的有状态小部件中的按钮来更改文本字段的字体大小。所以我尝试通过声明一个更改通知类来实现提供程序包,如下所示:

class ChangeNotifierList with ChangeNotifier {
  List<Widget> memeWidgets= new List();
  void add(Widget widget){
    memeWidgets.add(widget);
    notifyListeners();
  }
  void remove(Widget widget){
    memeWidgets.remove(widget);
    notifyListeners();
  }
  void increaseFontSize(StateTextField widget){
    widget.increaseFontSize();
    notifyListeners();

  }
}

并单击一个按钮,我更改了文本字段的字体大小,例如:

onTap: () {
                setState(() {
                  Provider.of<ChangeNotifierList>(context,listen: false)
                      .increaseFontSize(widget.textField);
                  //widget.textField.increaseFontSize();
                });
              }

我的小部件显示在堆栈中,堆栈定义如下:

Container(
                height: MediaQuery.of(context).size.height * 0.8,
                child: Consumer<ChangeNotifierList>(
                  builder: (context, value, child) {
                    return Stack(children: value.memeWidgets);
                  },
                ),
              )

我的 textField 小部件如下:

class StateTextField extends StatefulWidget {
  GlobalKey key = GlobalKey();
  final FocusNode focusNode = FocusNode();
  final Function(bool, Widget) callback;
  final String fontFamily = FontFamily.Arial.toString().split('.')[1];
  double fontSize = 18;
  final Function(bool) selected;
  final bool highlighted = false;
  bool hasFocus() {
    return focusNode.hasFocus;
  }

  increaseFontSize() {
    fontSize += 2;
  }

  decreasefontSize() {
    if (fontSize > 0) fontSize -= 2;
  }

  // increaseFontSize() {
  //   fontSize += 2;
  // }

  // decreasefontSize() {
  //   if (fontSize > 0) fontSize -= 2;
  // }

  StateTextField(
      {@required this.callback,
      @required this.selected,
      @required this.fontSize});
  @override
  _StateTextFieldState createState() => _StateTextFieldState();
}

我知道问题是因为更改后的 fontSize 没有传递给状态类,那么我该如何克服呢?

标签: androidflutterflutter-layoutflutter-provider

解决方案


推荐阅读