首页 > 建站教程 > dart >  dart笔记19:基于stream流的Flutter StreamBuilder组件正文

dart笔记19:基于stream流的Flutter StreamBuilder组件

dart笔记19:基于stream流的Flutter StreamBuilder组件,可以用来替代StatefulWidegtsetState方法,做到数据更新,实时渲染页面。
import 'dart:async';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'StreamBuilder示例',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  int _count = 0;
  final StreamController<int> _streamController = StreamController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StreamBuilder示例'),
      ),
      body: Container(
        child: Center(
          child: StreamBuilder(
            //流的来源
            stream: _streamController.stream,
            //将流的内容进行实时渲染
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              return snapshot.data == null
                  ? Text(
                      '0',
                      style: TextStyle(fontSize: 36.0),
                    )
                  : Text(
                      '${snapshot.data}',
                      style: TextStyle(fontSize: 36.0),
                    );
            },
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          //往stream流里面加数据
          _streamController.sink.add(++_count);
        },
      ),
    );
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}