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的关键工具,通过监听数据流的变化自动更新界面,显著简化了动态内容的渲染逻辑。它尤其适合需要持续数据更新的场景,能够有效降低代码复杂度并提升开发效率。

相关推荐
xzal123 小时前
python中,turtle基础知识笔记1
笔记·python·turtle
Lanren的编程日记4 小时前
Flutter鸿蒙应用开发:数据统计与分析功能集成实战
flutter·华为·harmonyos
鱼鳞_4 小时前
Java学习笔记_Day29(异常)
java·笔记·学习
九成宫6 小时前
IT项目管理期末复习——Chapter 8 项目质量管理
笔记·项目管理·软件工程
Flittly6 小时前
【SpringSecurity新手村系列】(3)自定义登录页与表单认证
java·笔记·安全·spring·springboot
Stella Blog6 小时前
狂神Java基础学习笔记Day04
java·笔记·学习
一只机电自动化菜鸟6 小时前
一建机电备考笔记(17) 常用设备—通用设备1(含考频+题型)
笔记·学习·职场和发展·生活·学习方法
bekote6 小时前
笔记|数据库
数据库·笔记
深蓝海拓6 小时前
基于QtPy (PySide6) 的PLC-HMI工程项目(十)框架初成的阶段总结
网络·笔记·python·学习·ui·plc
戏舟的嵌入式开源笔记7 小时前
LVGL部件应用笔记(基于正点原子教程,持续更新)
笔记