|
| 1 | +/// |
| 2 | +/// Created by NieBin on 2019/6/13 |
| 3 | +/// Github: https://github.com/nb312 |
| 4 | +/// Email: niebin312@gmail.com |
| 5 | +import "package:flutter/material.dart"; |
| 6 | +import 'package:flutter_widgets/const/_const.dart'; |
| 7 | + |
| 8 | +class StreamBuilderPage extends StatefulWidget { |
| 9 | + @override |
| 10 | + _StreamBuilderState createState() => _StreamBuilderState(); |
| 11 | +} |
| 12 | + |
| 13 | +class _StreamBuilderState extends State<StreamBuilderPage> { |
| 14 | + Stream<List<String>> _stream() => |
| 15 | + Stream<List<String>>.fromFuture(_futureList()); |
| 16 | + |
| 17 | + Future<List<String>> _futureList() async { |
| 18 | + return _listData; |
| 19 | + } |
| 20 | + |
| 21 | + List<String> _listData = [ |
| 22 | + "Hello", |
| 23 | + "World", |
| 24 | + "World", |
| 25 | + "World", |
| 26 | + "World", |
| 27 | + "World", |
| 28 | + "World", |
| 29 | + "World", |
| 30 | + "World", |
| 31 | + "World", |
| 32 | + "World", |
| 33 | + "World", |
| 34 | + "World", |
| 35 | + "World", |
| 36 | + "World", |
| 37 | + "World", |
| 38 | + "World", |
| 39 | + "World", |
| 40 | + "World", |
| 41 | + "World", |
| 42 | + "World", |
| 43 | + "World", |
| 44 | + ]; |
| 45 | + |
| 46 | + Widget _streamBuildList() => StreamBuilder( |
| 47 | + builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) { |
| 48 | + switch (snapshot.connectionState) { |
| 49 | + case ConnectionState.none: |
| 50 | + return Text('Press button to start.'); |
| 51 | + case ConnectionState.active: |
| 52 | + case ConnectionState.waiting: |
| 53 | + return Text('Awaiting result...'); |
| 54 | + case ConnectionState.done: |
| 55 | + if (snapshot.hasError) return Text('Error: ${snapshot.error}'); |
| 56 | + return ListView.builder( |
| 57 | + itemCount: snapshot.data.length, |
| 58 | + itemBuilder: (context, index) => Container( |
| 59 | + constraints: BoxConstraints.expand(height: 100), |
| 60 | + color: index % 2 == 0 ? RED_LIGHT : PURPLE, |
| 61 | + child: Text( |
| 62 | + snapshot.data[index], |
| 63 | + style: TextStyle(color: TEXT_BLACK, fontSize: 20), |
| 64 | + ), |
| 65 | + )); |
| 66 | + } |
| 67 | + return null; // unreachable |
| 68 | + }, |
| 69 | + stream: _stream(), |
| 70 | + ); |
| 71 | + |
| 72 | + @override |
| 73 | + Widget build(BuildContext context) { |
| 74 | + return Scaffold( |
| 75 | + appBar: AppBar( |
| 76 | + title: Text(PageName.ASYNC_STREAM_BUILDER), |
| 77 | + ), |
| 78 | + body: _streamBuildList(), |
| 79 | + ); |
| 80 | + } |
| 81 | +} |
0 commit comments