FutureBuilder没有建立

时间:2018-12-13 14:05:23

标签: dart

您知道为什么在启动流并返回到Future时未调用以下FutureBuilder吗?

注意:我知道有很多方法可以通过流等解决。这是为了学习,所以,如果您知道为什么,我想知道-谢谢。

// import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:flutter/material.dart';

class MyFutureClass {
  Future<String> myF;

  setMyF() {
    this.myF = Future.value("Hello F");
  }

  Future<String> getMyF() {
    return myF;
  }
}

class MyFutureWidget extends StatelessWidget {
  MyStreamWidget();

  final _myStreamClass = MyStreamClass();

  // var stream = countStream(10);
  // var sum = await sumStream(stream);
  // print(sum); // 55

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Row(
        children: [
          RaisedButton(
            child: Text("Add to future"),
            onPressed: () {
              _myStreamClass.setMyF();
            },
          ),
          FutureBuilder(
            // future: _myStreamClass.getMyF(),
            future: _myStreamClass.myF),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data);
              } else {
                return Text("No data");
              }
            },
          ),
        ]
            .map((c) => Container(
                  padding: EdgeInsets.all(8.0),
                  child: c,
                ))
            .toList(),
      ),
    );
  }
}

使用 StateFullWidget :刚尝试使用StateFullWidget,结果相同-不调用FutureBuilder吗?

// import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:flutter/material.dart';

class MyStreamClass {
  Future<String> myF;

  setMyF() {
    this.myF = Future.value("Hello F");
    this.myF.then((v) {
      print(v);
    });
  }

  Future<String> getMyF() {
    return myF;
  }
}

class MyStreamWidget extends StatefulWidget {

   @override
  _MyStreamWidget createState() => _MyStreamWidget();

}

class _MyStreamWidget extends State<MyStreamWidget> {
  final _myStreamClass = MyStreamClass();

  // var stream = countStream(10);
  // var sum = await sumStream(stream);
  // print(sum); // 55

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Row(
        children: [
          RaisedButton(
            child: Text("Add to future"),
            onPressed: () {
              _myStreamClass.setMyF();
            },
          ),
          FutureBuilder(
            future: _myStreamClass.myF,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data);
              } else {
                return Text("No data");
              }
            },
          ),
        ]
            .map((c) => Container(
                  padding: EdgeInsets.all(8.0),
                  child: c,
                ))
            .toList(),
      ),
    );
  }
}

0 个答案:

没有答案