dart - 如何确保在构建 Widget 之前加载异步函数?

标签 dart flutter

我有一个屏幕,上面有一些关于用户的信息。

在我的构建小部件中,我有这个:

Column
 (
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>
    [
    Text('User Points', style: TextStyle(color: Colors.blueAccent)),
    Text('${this.user.points}', style: TextStyle(color: Colors.black, fontWeight: FontWeight.w700, fontSize: 34.0))
    ],
 ),

而且我有一个功能,可以在每次用户访问时更新仪表板。

void updateDashboard() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var api_key = prefs.getString('api_key');
    var userID = prefs.getInt('userID');

    var res = await http.post(('http://myApp.com/getDashboardPreferences/'+userID.toString() + '/' + api_key),
        headers: {
          "Accept": "application/json",
          "content-type": "application/json"
        });

    this.user = User.fromJson(json.decode(res.body));

    setState(() {
      if (res.statusCode == 200) { 
        this.user.setPoints(this.user.points);
      } else {
        print("Something is wrong");
      }
    });

  }

在 initstate 中我调用了这个函数:

@override
  void initState() {
    updateDashboard();
    super.initState();
  }

这有效,但是,我得到 ${this.user.points}null 几秒钟(我得到那个警告屏幕)然后它已加载,一切正常。我想这是因为我的函数是 async...但是我如何确保在渲染 Widget build() 之前调用此 updateDashboard() > ?

最佳答案

如果你不想使用 FutureBuilder 那么你可以做类似的事情

if(done)
    Column(  /* whatever */ )
else
    Center(child: CircularProgressIndicator())
void updateDashboard() async{
    /* whatever */

     if (res.statusCode == 200) { 
        setState(() {
           this.user.setPoints(this.user.points);

           done = true;

      });          
 }

@override
  void initState() {
    /* whatever */
    done = false;
  }

关于dart - 如何确保在构建 Widget 之前加载异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55939288/

相关文章:

dart - http.get() 不在 header 中添加我的参数

dart - Flutter:类型 'List<dynamic>' 不是类型 'List<Widget>' 的子类型

android - flutter 中一个屏幕上有两个 TabBar

flutter - 调用 Firebase.initializeApp() 返回 '(PlatformException(null-error, Host platform returned null value for non-null return value., null, null))'

flutter - 抽象类不能被实例化!在身份验证 block 中

xml - 在Dart/Flutter中解析巨大的(3Gb)XML

flutter - Flutter-何时使用setState()安装?

dart - 在 Dart.lang 中需要一张 map 的 map

flutter - 接收方:空E/flutter(4835):尝试调用:[] (“Data”)

android - 在 Flutter 中的操作栏和标题之间添加一些空间