首页 > 解决方案 > Flutter setState() 只调用一次

问题描述

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget{
  @override
  State createState() => Comeback();
}

class Comeback extends State<MyApp>{
  Widget hello(BuildContext context){
    var listInsults = ['no you', 'but this applies to you more than me', 'that insult was horrible'];
    var finalVar = listInsults.toList()..shuffle();
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            CircleAvatar(
              child: Text(
                "XD"
              )
            ),
            Text(
              finalVar[0]
            )
          ]
        )
      ],
    );
  }
  Widget build(BuildContext context){
    var listy = 0;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            "hi"
          )
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) => hello(context),
                itemCount: listy
              ),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: TextFormField(
                    decoration: InputDecoration(
                      hintText: "Insult me plz!"
                    )
                  ),
                ),
                RaisedButton(
                    onPressed: () {
                        setState(() {
                          listy++;
                          //where program is being printed
                          print(listy);
                        });

                    },
                    child: Icon(Icons.add_circle_outline),
                    highlightColor: Colors.amber[600]),
              ],
            )
          ],
        )
      )
    );
  }
}

基本上,我正在尝试制作一个卷土重来的生成器,用户通过文本框侮辱程序,程序通过 ListView.builder 将它们烤回来。不幸的是,在测试我的代码时,没有显示程序的侮辱。正如您在代码中的注释下方看到的那样,我试图查看变量 listy(用于更改列表中的项目数)发生了什么,并意识到它只更新了一次。这是终端:

I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/chatty  ( 4632): uid=10091(com.example.comeback_generator) Thread-2 identical 2 lines
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/chatty  ( 4632): uid=10091(com.example.comeback_generator) Thread-2 identical 1 line
I/flutter ( 4632): 1

从上面看,您可以看到程序显然没有更新变量 listy。如果是这样,打印的数字就会增加一。我尝试从一个类似项目中复制和粘贴代码,该项目通过更改变量和删除不必要的代码来工作和修改它。

这是我复制并粘贴的代码:

onPressed: () {
                            if(!products.contains(myController.text.toLowerCase()) && !products.contains(myController.text.toUpperCase()) && !products.contains(myController.text)) {
                              setState(() {
                                products.add(myController.text);
                                _save();
                                _read();
                              });
                            }
},

这是我修改它的方法:

setState(() {
          listy++;
          print(listy);
});

修改后程序仍然有同样的错误。

我的程序有什么问题?为什么程序出错?我该如何解决这个问题并避免将来出现类似的错误和不一致?

请记住,我是颤振的初学者,我很容易出错。

标签: flutterdart

解决方案


那是因为每次刷新小部件时,build都会调用该方法,然后将变量 listy 再次分配给 0。

Widget build(BuildContext context){
    var listy = 0;

要解决您的问题,只需将声明移到您的build方法之外,如下所示:

 var listy = 0;

 Widget build(BuildContext context){
   ...



推荐阅读