为什么我的Flutter应用中变量没有更新?

huangapple go评论62阅读模式
英文:

Why variables aren't updating in my Flutter app?

问题

I'm new to Flutter and I'm building an array of rows and columns with buttons, ListTiles and some gestures.

When I press the button "Agregar" and I select the "H_AND_H" option, the next cell should update with the "valorSeleccionado1" value but the Text doesn't appear until I do a hot reload in VS Code. Also, I want that two lines appear when I tap one of the rows but it's the same case, those lines don't appear until I do a hot reload.

I'm using global variables because I couldn't find another way to pass values from BotonAgregar to MyHomePage.

英文:

I'm new to Flutter and I'm building an array of rows and columns with buttons, ListTiles and some gestures.

When I press the button "Agregar" and I select the "H_AND_H" option, the next cell should update with the "valorSeleccionado1" value but the Text doesn't appear until I do a hot reload in VS Code.
Also I want that two lines appear when I tap one of the rows but it's the same case, those lines don't appear until I do a hot reload.

I'm using global variables because I couldn't find another way to pass values from BotonAgregar to MyHomePage.

// Global variable
String valorSeleccionado1 = ''; 
String imgCompuerta1 = '';

class BotonAgregar extends StatefulWidget {
  const BotonAgregar({
    Key? key,
  }) : super(key: key);

  @override
  State<BotonAgregar> createState() => _BotonAgregarState();
}

class _BotonAgregarState extends State<BotonAgregar> {
  int _idCompuertaAND = 0;
  String _compuertaSeleccionada1 = '';

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: SizedBox(
                  height: 560,
                  child: Column(children: [
                    ListTile(
                        title: const Text("H_AND_H"),
                        leading: Image.asset(
                            'assets/images/Miniatura/H_MinAnd_H.bmp'),
                        onTap: () {
                          setState(() {
                            _idCompuertaAND += 1;
                            _compuertaSeleccionada1 = '2_AND_$_idCompuertaAND';
                            imgCompuerta1 =
                                'assets/images/Miniatura/H_AND_H_APK_2.bmp';
                            valorSeleccionado1 = _compuertaSeleccionada1;
                          });
                          Navigator.pop(context);
                        }),
                  ]),
                ),
              );
            });
      },
      child: const Text("Agregar", textScaleFactor: 0.8),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _border1 = [255, 255, 255];
  var _border2 = [255, 255, 255];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(5.0),
          child: Column(
            children: [
              Expanded(
                // Permite el desplazamiento en vertical
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  // Permite el desplazamiento en horizontal
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    // Color de fondo de toda la tabla
                    child: Container(
                      //color: Colors.white,
                      color: const Color.fromARGB(255, 193, 191, 254),
                      width: 1310,
                      height: 1044,
                      child: Column(
                        children: [
                          // Fila 1 de la tabla
                          GestureDetector(
                            onTap: () {
                              _border1 = [0, 255, 0];
                              _border2 = [255, 0, 0];
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                border: Border(
                                  top: BorderSide(
                                    color: (Color.fromARGB(255, _border1[0],
                                        _border1[1], _border1[2])),
                                    width: 3,
                                  ),
                                  bottom: BorderSide(
                                    color: (Color.fromARGB(255, _border2[0],
                                        _border2[1], _border2[2])),
                                    width: 3,
                                  ),
                                ),
                              ),
                              child: Row(
                                children: [
                                  Column(
                                    children: [
                                      Container(
                                        width: 80,
                                        height: 36,
                                        padding: const EdgeInsets.all(4),
                                        color: Colors.white,
                                        child: const BotonAgregar(),
                                      ),
                                    ],
                                  ),
                                  Column(
                                    children: [
                                      Container(
                                        width: 80,
                                        height: 36,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          image: DecorationImage(
                                            image: AssetImage(imgCompuerta1),
                                            alignment: Alignment.center,
                                          ),
                                        ),
                                        child: Center(
                                          child: Text(
                                            valorSeleccionado1,
                                            style: const TextStyle(
                                                fontSize: 12,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),

I've tried to enclose the Container that contains the Text with the variable "valorSeleccionado1" in a StatefulWidget with its own State but it's the same case, the value doesn't update.

答案1

得分: 0

以下是您提供的代码的翻译部分:

因为您的BotonAgregar小部件通过setState进行重建并不意味着MyHomePage会重新构建。

您应该找出Flutter的状态管理方式。

如果您还没有找到,我有以下解决方案:

class BotonAgregar extends StatefulWidget {
  const BotonAgregar({
    Key? key,
    required this.imgCompuerta1Change,
    required this.valorSeleccionado1,
  }) : super(key: key);

  final Function(String) imgCompuerta1Change;
  final Function(String) valorSeleccionado1;

  @override
  State<BotonAgregar> createState() => _BotonAgregarState();
}

class _BotonAgregarState extends State<BotonAgregar> {
  int _idCompuertaAND = 0;
  String _compuertaSeleccionada1 = '';

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: SizedBox(
                  height: 560,
                  child: Column(children: [
                    ListTile(
                        title: const Text("H_AND_H"),
                        leading: Image.asset(
                            'assets/images/Miniatura/H_MinAnd_H.bmp'),
                        onTap: () {
                          _idCompuertaAND += 1;
                          _compuertaSeleccionada1 = '2_AND_$_idCompuertaAND';
                          widget.imgCompuerta1Change(
                              'assets/images/Miniatura/H_AND_H_APK_2.bmp');
                          widget.valorSeleccionado1(_compuertaSeleccionada1);
                          Navigator.pop(context);
                        }),
                  ]),
                ),
              );
            });
      },
      child: const Text("Agregar", textScaleFactor: 0.8),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _border1 = [255, 255, 255];
  var _border2 = [255, 255, 255];
  String valorSeleccionado1 = '';
  String imgCompuerta1 = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: Column(children: [
                  Expanded(
                      // Allows vertical scrolling
                      child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          // Allows horizontal scrolling
                          child: SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              // Background color of the entire table
                              child: Container(
                                  //color: Colors.white,
                                  color:
                                      const Color.fromARGB(255, 193, 191, 254),
                                  width: 1310,
                                  height: 1044,
                                  child: Column(children: [
                                    // Row 1 of the table
                                    GestureDetector(
                                        onTap: () {
                                          _border1 = [0, 255, 0];
                                          _border2 = [255, 0, 0];
                                        },
                                        child: Container(
                                            decoration: BoxDecoration(
                                              border: Border(
                                                top: BorderSide(
                                                  color: (Color.fromARGB(
                                                      255,
                                                      _border1[0],
                                                      _border1[1],
                                                      _border1[2])),
                                                  width: 3,
                                                ),
                                                bottom: BorderSide(
                                                  color: (Color.fromARGB(
                                                      255,
                                                      _border2[0],
                                                      _border2[1],
                                                      _border2[2])),
                                                  width: 3,
                                                ),
                                              ),
                                            ),
                                            child: Row(children: [
                                              Column(
                                                children: [
                                                  Container(
                                                    width: 80,
                                                    height: 36,
                                                    padding:
                                                        const EdgeInsets.all(4),
                                                    color: Colors.white,
                                                    child: BotonAgregar(
                                                      imgCompuerta1Change:
                                                          (value) {
                                                        setState(() =>
                                                            imgCompuerta1 =
                                                                value);
                                                      },
                                                      valorSeleccionado1:
                                                          (value) => setState(() =>
                                                              valorSeleccionado1 =
                                                                  value),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              Column(
                                                children: [
                                                  Container(
                                                    width: 80,
                                                    height: 36,
                                                    decoration: BoxDecoration(
                                                      color: Colors.white,
                                                      image: DecorationImage(
                                                        image: AssetImage(
                                                            imgCompuerta1),
                                                        alignment:
                                                            Alignment.center,
                                                      ),
                                                    ),
                                                    child: Center(
                                                      child: Text(
                                                        valorSeleccionado1,
                                                        style: const TextStyle(
                                                            fontSize: 12,
                                                            fontWeight:
                                                                FontWeight
                                                                    .bold),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ])))
                                  ])))))))
                ]))));
  }
}

希望这有助于您理解代码的翻译部分。如果您有任何其他问题,请随时提出。

英文:

Because your BotonAgregar widget rebuild through setState does not mean MyHomePage rebuilt

You should find out state management of flutter,

If you haven't found out yet,I have the solution for your problem as follows:

class BotonAgregar extends StatefulWidget {
  const BotonAgregar({
    Key? key,
    required this.imgCompuerta1Change,
    required this.valorSeleccionado1,
  }) : super(key: key);

  final Function(String) imgCompuerta1Change;
  final Function(String) valorSeleccionado1;

  @override
  State&lt;BotonAgregar&gt; createState() =&gt; _BotonAgregarState();
}

class _BotonAgregarState extends State&lt;BotonAgregar&gt; {
  int _idCompuertaAND = 0;
  String _compuertaSeleccionada1 = &#39;&#39;;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: SizedBox(
                  height: 560,
                  child: Column(children: [
                    ListTile(
                        title: const Text(&quot;H_AND_H&quot;),
                        leading: Image.asset(
                            &#39;assets/images/Miniatura/H_MinAnd_H.bmp&#39;),
                        onTap: () {
                          _idCompuertaAND += 1;
                          _compuertaSeleccionada1 = &#39;2_AND_$_idCompuertaAND&#39;;
                          widget.imgCompuerta1Change(
                              &#39;assets/images/Miniatura/H_AND_H_APK_2.bmp&#39;);
                          widget.valorSeleccionado1(_compuertaSeleccionada1);
                          Navigator.pop(context);
                        }),
                  ]),
                ),
              );
            });
      },
      child: const Text(&quot;Agregar&quot;, textScaleFactor: 0.8),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  var _border1 = [255, 255, 255];
  var _border2 = [255, 255, 255];
  String valorSeleccionado1 = &#39;&#39;;
  String imgCompuerta1 = &#39;&#39;;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: Column(children: [
                  Expanded(
                      // Permite el desplazamiento en vertical
                      child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          // Permite el desplazamiento en horizontal
                          child: SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              // Color de fondo de toda la tabla
                              child: Container(
                                  //color: Colors.white,
                                  color:
                                      const Color.fromARGB(255, 193, 191, 254),
                                  width: 1310,
                                  height: 1044,
                                  child: Column(children: [
                                    // Fila 1 de la tabla
                                    GestureDetector(
                                        onTap: () {
                                          _border1 = [0, 255, 0];
                                          _border2 = [255, 0, 0];
                                        },
                                        child: Container(
                                            decoration: BoxDecoration(
                                              border: Border(
                                                top: BorderSide(
                                                  color: (Color.fromARGB(
                                                      255,
                                                      _border1[0],
                                                      _border1[1],
                                                      _border1[2])),
                                                  width: 3,
                                                ),
                                                bottom: BorderSide(
                                                  color: (Color.fromARGB(
                                                      255,
                                                      _border2[0],
                                                      _border2[1],
                                                      _border2[2])),
                                                  width: 3,
                                                ),
                                              ),
                                            ),
                                            child: Row(children: [
                                              Column(
                                                children: [
                                                  Container(
                                                    width: 80,
                                                    height: 36,
                                                    padding:
                                                        const EdgeInsets.all(4),
                                                    color: Colors.white,
                                                    child: BotonAgregar(
                                                      imgCompuerta1Change:
                                                          (value) {
                                                        setState(() =&gt;
                                                            imgCompuerta1 =
                                                                value);
                                                      },
                                                      valorSeleccionado1:
                                                          (value) =&gt; setState(() =&gt;
                                                              valorSeleccionado1 =
                                                                  value),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              Column(
                                                children: [
                                                  Container(
                                                    width: 80,
                                                    height: 36,
                                                    decoration: BoxDecoration(
                                                      color: Colors.white,
                                                      image: DecorationImage(
                                                        image: AssetImage(
                                                            imgCompuerta1),
                                                        alignment:
                                                            Alignment.center,
                                                      ),
                                                    ),
                                                    child: Center(
                                                      child: Text(
                                                        valorSeleccionado1,
                                                        style: const TextStyle(
                                                            fontSize: 12,
                                                            fontWeight:
                                                                FontWeight
                                                                    .bold),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ])))
                                  ])))))
                ]))));
  }
}

huangapple
  • 本文由 发表于 2023年5月25日 09:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定