更新状态不会影响FutureBuilder小部件

时间:2020-02-04 06:26:05

标签: flutter dart

我一直在尝试更新自己定义的Report小部件,该小部件包装在FutureBuilder中(因为它取决于API响应中的数据)。每当我单击MiniReport中的ListView小部件之一时,我都希望Report进行更新以显示来自相应JSON数据的相关信息。我知道状态正在更新并且正在重建屏幕,因为Text('${this.highlight}')正在更新,但是无论出于何种原因,Report内部的FutureBuilder都没有更新。任何帮助将不胜感激!

P.S。我仍然是一个初学者,所以这可能不是做事情的最佳方法。欢迎任何建议!

代码:

class MainScreen extends StatefulWidget {
  final List<Future> requests;

  MainScreen(this.requests);

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

class _MainScreenState extends State<MainScreen> {
  int highlight;
  List<Future> reqs;
  List<Widget> list;

  @override
  void initState() {
    highlight = 0;
    reqs = widget.requests;

    list = [];
    for (var i = 0; i < reqs.length; i++) {
      Widget fb = FutureBuilder(
        future: reqs[i],
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return GestureDetector(
              child: MiniReport(data: snapshot.data),
              onTap: () {
                setState(() {
                  this.highlight = i;
                });
              },
            );
          } else {
            return SizedBox();
          }
        },
      );

      list.add(fb);
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return WillPopScope(
      onWillPop: () async => false,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          image: DecorationImage(
            image: AssetImage('images/bg.jpg'),
            fit: BoxFit.fitHeight,
          ),
        ),
        child: Scaffold(
          backgroundColor: Color(0xAA000000),
          body: SafeArea(
            child: Column(
              children: <Widget>[
                Text('${this.highlight}'),
                Expanded(
                  flex: 4,
                  child: FutureBuilder(
                    future: reqs[highlight],
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      if (snapshot.hasData) {
                        return Report(data: snapshot.data);
                      } else {
                        return SizedBox();
                      }
                    },
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: GestureDetector(
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      children: this.list,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

0 个答案:

没有答案