Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter get the value of a widget class variable

I have this widget:

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;
        },
      ),
    );
  }
}

And in my page, where i call this widget, i want to assign the value of ‘valor’ to another variable.
How can i do that ?
Now i’m only calling the widget like this in my widget tree :

 TextBox(
   largura: 100, 
   tamanhoLetra: 25,
 )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is not possible to get a variable from a child widget into a parent widget, this is not what you are supposed to do, instead pass an onChanged callback into the Textbox widget and edit valor from there:

on the parent widget:

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),
    );
  }
}

Then on your child widget:

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

  final void Function(String) onValorChanged;

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

[...]

You have now "moved the state up", making it so the parent widget stores the valor variable instead of the child widget.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading