Flutter 获取一个 widget class 变量的值

Flutter get the value of a widget class variable

我有这个小部件:

import 'package:flutter/material.dart';

class TextBox extends StatelessWidget {

  late var valor;
  late var largura;
  late var tamanhoLetra;

  TextBox({
    required this.largura,
    required this.tamanhoLetra
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: largura,
      child: TextField(
        style: TextStyle(
          fontSize: tamanhoLetra,
        ),
        textAlign: TextAlign.left,
        onChanged: (String text) {
          valor = text;
        },
      ),
    );
  }
}

在我调用此小部件的页面中,我想将 'valor' 的值分配给另一个变量。
我怎样才能做到这一点 ?
现在我只在我的小部件树中调用这样的小部件:

 TextBox(
   largura: 100, 
   tamanhoLetra: 25,
 )

不可能从子窗口小部件获取变量到父窗口小部件,这不是您应该做的,而是将 onChanged 回调传递到文本框窗口小部件并从那里编辑 valor :

在父小部件上:

class MyWidget extends StatefulWidget {

  const MyWidget({Key? key}) : super(key: key);

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

class _MyWidgetState extends State<MyWidget> {

  String valor = '';

  @override
  Widget build(BuildContext context) {
    return TextBox(
      largura: 100, 
      tamanhoLetra: 25,
      onValorChanged: (String value) => setState(() => valor = value),
    );
  }
}

然后在您的子部件上:

  TextBox({Key? key, required this.onValorChanged}): super(key: key);

  final void Function(String) onValorChanged;

[...]
      TextField(
        style: TextStyle(
          fontSize: tamanhoLetra,
        ),
        textAlign: TextAlign.left,
        onChanged: onValorChanged,
      ),

[...]

您现在已经“向上移动状态”,使父小部件存储 valor 变量而不是子小部件。

你的 TextBox 中有 encapsulated valor,所以你实际上应该避免直接使用这个值。

所以,您应该做两件事:

  1. 提升状态(即将 valor 移至 TextBox 的调用者)
  2. 使用回调在 TextBox 之外设置状态

import 'package:flutter/material.dart';

class TextPage extends StatefulWidget {...}

class _TextPageState extends State<TextPage> {
    String valor = '';

    @override
    Widget build(BuildContext context) {
        return TextBox(
            largura: MediaQuery.of(context).size.width,
            tamanhoTexto: 20,
            onChanged: (texto) => setState(() {
                valor = texto;
            }),
        );
    }
}

class TextBox extends StatelessWidget {

  // late var valor; // this no longer exists here
  final void Function(String newText) onChange; 

  // you should use final instead of late here because this class is immutable
  // it's not recommended to use var where the variable is not of dynamic type
  final double largura;
  final double tamanhoLetra;

  TextBox({
    required this.largura,
    required this.tamanhoLetra
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: largura,
      child: TextField(
        style: TextStyle(
          fontSize: tamanhoLetra,
        ),
        textAlign: TextAlign.left,
        onChanged: onChanged,
      ),
    );
  }
}