rozerro
rozerro

Reputation: 7168

How to update a widget after async reciever done?

How to update text widget after async reciever done?

  //it is a stateless widget
  @override
  Widget build(BuildContext context) {
    String appName = '';

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      appName = packageInfo.appName;
      print('$appName');
    });

    return Column(
        children: <Widget>[
          Text('$appName'), //how to update this widget?

Upvotes: 0

Views: 118

Answers (2)

CLucera
CLucera

Reputation: 1191

You can simply use a FutureBuilder Widget of the week

just wrap your Text and check the snapshot value

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
       child: FutureBuilder<PackageInfo>(
         future: PackageInfo.fromPlatform(),
         builder: (context, snapshot) {
           return Text(snapshot.hasData ? snapshot.data.appName : "");
         }
       ),
      ),

    );
  }

Upvotes: 0

Gaurav Gupta
Gaurav Gupta

Reputation: 11

Use stateful widget and set the state like this

PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
  setState(() {
    appName = packageInfo.appName;
  });
  print('$appName');
});

Upvotes: 1

Related Questions