Flutter:setState()对于列表类型无效

时间:2020-02-08 07:51:18

标签: flutter gridview dart setstate

我的兄弟们!抱歉,我的英语太糟糕了,希望您能理解。

我无法使用setState((){})更新列表类型的变量!我尝试修复了很长时间,但失败了。

这是我的演示代码,您可以运行以下代码:

import 'package:flutter/material.dart';

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

class TestListUpdate extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TestListUpdatePage(),
    );
  }
}

class TestListUpdatePage extends StatefulWidget {
  TestListUpdatePage({Key key}) : super(key: key);

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

class _TestListUpdatePageState extends State<TestListUpdatePage> {
  int _counter = 0;
  List<Widget> _list = [];

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void _addPic() {

    setState(() {
      _list.add(
        ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.network(
              'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581151314271&di=6d55b078b319acc55d081685e3208b6c&imgtype=0&src=http%3A%2F%2Fimg-download.pchome.net%2Fdownload%2F1k1%2Fe0%2F32%2Fol8r6m-1sqx.jpg',
              fit: BoxFit.cover,
            )),
      );
    });
    print(_list.length);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            Container(
                height: 100,
                child: GridView.count(
                  physics: NeverScrollableScrollPhysics(),
                  crossAxisCount: 4,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: 5,
                  children: _list,
                ))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _incrementCounter();
          _addPic();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}


当我按添加按钮时,数字已更改。但是网格的数据没有改变。.

请帮助我!谢谢你!

2 个答案:

答案 0 :(得分:0)

将列表初始化移至initState函数

更改:

List<Widget> _list = [];

收件人:

List<Widget> _list;

在initState函数中初始化列表:

@override
void initState() {
 super.initState();
 _list = [];
}

答案 1 :(得分:0)

您可以使用“ GridView.builder”。您的“ setState”正在工作。 “ GridView.count”不起作用。

var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
{
    sbc.Host("rabbitmq://localhost/");

    sbc.OverrideDefaultBusEndpointQueueName("endpoint");
});