0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Flutter]特定のウィジェットを非同期で処理する[StreamBuilder / FutureBuilder]

Posted at

ウィジェットの値をDBやAPI等から取得する必要がある場合、一部だけ非同期に処理をする必要がある場合がある。

こういった場合、特定のウィジェットをFutureBuilderもしくはStreamBuilderで囲むことによって非同期処理が可能になる。

・StreamBuilder・・・データの変更をリアムタイムで検知し、自動的に再描画したい場合
・FutureBuilder・・・データの変更をリアルタイムで検知せず、自動的に再描画したくない場合

[FutureBuilder]

class HomeScreen extends StatelessWidget {
  final displayText =
      FirebaseFirestore.instance.collection('cities').doc('LA').get();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Memo Pad'),
      ),
      body: Center(
        child: FutureBuilder(
          future: displayText,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            return Text(
              snapshot.data['name'],
              style: const TextStyle(fontSize: 24),
            );
          },
        ),
      ),
    );
  }
}

[StreamBuilder]

class HomeScreen extends StatelessWidget {
  final displayText =
      FirebaseFirestore.instance.collection('cities').doc('LA').snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Memo Pad'),
      ),
      body: Center(
        child: StreamBuilder(
          stream: displayText,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            return Text(
              snapshot.data['name'],
              style: const TextStyle(fontSize: 24),
            );
          },
        ),
      ),
    );
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?