Flutter笔记--StreamBuilder

Flutter开发中,StreamBuilder是一个用于构建响应式用户界面,它是一个基于数据流(Stream)动态构建UI的Widget。它通过监听Stream发出的数据事件,在每次新数据到达时自动触发UI重建,确保界面与数据状态实时同步。总结如下:

API:

Dart 复制代码
StreamBuilder<T>({
  Key? key,
  required Stream<T> stream,        // 要监听的数据流
  T? initialData,                   // 初始值(可选)
  required AsyncWidgetBuilder<T> builder, // 构建UI的回调
})

处理逻辑:

订阅Stream:接收数据流(如网络请求、用户输入等)。

捕获快照:通过AsyncSnapshot对象获取当前数据、连接状态或错误信息。

动态渲染:根据快照内容返回不同的Widget树。
使用场景:

1 实时更新UI

2 处理异步操作

栗子:

Dart 复制代码
import 'dart:async';
import 'package:flutter/material.dart';

void main() => runApp(const StreamCounterApp());

class StreamCounterApp extends StatelessWidget {
  const StreamCounterApp({super.key});
  @override
  Widget build(BuildContext context) {

    final counterStream = Stream.periodic(const Duration(seconds: 1),(count) => count+1).take(10);
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('StreamBuilder Counter'),),
        body: Center(
          child: StreamBuilder(stream: counterStream
              ,initialData: 0
              , builder: (context,snapshot) {
                if(snapshot.connectionState == ConnectionState.waiting) {
                  return const Text('启动中...');
                }
                if(snapshot.hasError) {
                  return Text('错误: ${snapshot.error}');
                }
                if(snapshot.connectionState == ConnectionState.done) {
                  return const Text('计数结束!',style: TextStyle(color: Colors.green),);
                }
                return Text(
                  '当前值: ${snapshot.data}',
                  style: const TextStyle(fontSize: 24),
                );
              }),
        ),
      ),
    );
  }
}
Dart 复制代码
import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';

void main() => runApp(const SineWaveApp());

class SineWaveApp extends StatelessWidget {
  const SineWaveApp({super.key});

  @override
  Widget build(BuildContext context) {
    final timeStream = Stream.periodic(const Duration(milliseconds: 100), (_) => DateTime.now().millisecondsSinceEpoch);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('动态正弦')),
        body: StreamBuilder<int>(
          stream: timeStream,
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const SizedBox();

            final t = snapshot.data! / 1000.0; 
            return CustomPaint(
              size: const Size(double.infinity, 200),
              painter: SineWavePainter(t),
            );
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {}, 
          child: const Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}

class SineWavePainter extends CustomPainter {
  final double time;

  SineWavePainter(this.time);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    final points = <Offset>[];
    final width = size.width;
    final height = size.height;
    final centerY = height / 2;

    for (int i = 0; i <= width.toInt(); i++) {
      final x = i.toDouble();
      final y = centerY + 50 * sin(2 * pi * 0.5 * time - 2 * pi * x / 100);
      points.add(Offset(x, y));
    }

    if (points.length > 1) {
      canvas.drawPoints(PointMode.polygon, points, paint);
    }
  }

  @override
  bool shouldRepaint(covariant SineWavePainter oldDelegate) {
    return oldDelegate.time != time; 
  }
}

简单来说,StreamBuilder是Flutter中实现响应式UI的关键工具,通过监听数据流的变化自动更新界面,显著简化了动态内容的渲染逻辑。它尤其适合需要持续数据更新的场景,能够有效降低代码复杂度并提升开发效率。

相关推荐
薛定e的猫咪8 小时前
因果推理研究方向综述笔记
人工智能·笔记·深度学习·算法
AOwhisky8 小时前
虚拟化技术学习笔记
linux·运维·笔记·学习·虚拟化技术
一只机电自动化菜鸟8 小时前
一建机电备考笔记(33) 机电专业技术(起重技术-吊装方案)(含考频+题型)
经验分享·笔记·学习·职场和发展·课程设计
小陈phd10 小时前
多模态大模型学习笔记(四十)——从“看字”到“懂结构”:版面分析与表格解析技术全解
笔记·学习
xuhaoyu_cpp_java10 小时前
SpringMVC学习(二)
java·经验分享·笔记·学习·spring
噜噜噜阿鲁~11 小时前
python学习笔记 | 9.2、模块-安装第三方模块
笔记·python·学习
我胖虎不答应!!12 小时前
Three.js开发思想笔记
javascript·笔记·three.js
程序leo源12 小时前
C语言知识总结
c语言·开发语言·c++·经验分享·笔记·青少年编程·c#
羊群智妍13 小时前
2026年GEO优化实战:AI搜索优化监测工具全解析
笔记
中屹指纹浏览器13 小时前
2026浏览器插件指纹溯源机制与插件环境安全优化实战指南
经验分享·笔记