StreamBuilder
组件,可以用来替代StatefulWidegt
的setState
方法,做到数据更新,实时渲染页面。
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(); } }
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!