StreamContrller实现局部刷新和生产者消费者模式

1、定义一个ViewModel便于StreamControlerl被多个类访问
import 'dart:async';

class StreamViewModel{
  int count=0;
  final StreamController streamController = StreamController.broadcast();

}

2在HomePage中初始化ViewModel,并将ViewMode传递到PageOne,pageTwo中;并监听Count值的变化

import 'dart:async';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demos/page1.dart';
import 'package:flutter_demos/page2.dart';
import 'package:flutter_demos/strem_viewmodel.dart';
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  State createState() {
    return _TestABPageState();
  }
}
class _TestABPageState extends State {
  late StreamViewModel viewModel;

  @override
  void initState() {
    super.initState();
    viewModel=StreamViewModel();
  }

  @override
  void dispose() {
    super.dispose();
    viewModel.streamController.close();
  }
  @override
  Widget build(BuildContext context) {
    ///页面主体脚手架
    return Scaffold(
      appBar: AppBar(
        title: const Text("homepage"),
      ),
      body:Column(
        children: [
          buildStreamBuilder(),
          TextButton(onPressed: (){
            Navigator.push(context, new MaterialPageRoute(builder: (context)=>new PageOne(viewModel: viewModel,)));
          }, child:const Text(
            'page1',
            style: TextStyle(fontSize: 22, color: Colors.blue),
          ) ) ,
          TextButton(onPressed: (){
            Navigator.push(context, new MaterialPageRoute(builder: (context)=>new PageTwo(viewModel: viewModel,)));

          }, child:const Text(
            'page2',
            style: TextStyle(fontSize: 22, color: Colors.blue),
          ) ),

        ],
      )

    );
  }

  ///代码清单1-1
  /// 监听Stream,每次值改变的时候,更新Text中的内容
  StreamBuilder buildStreamBuilder() {
    return
      StreamBuilder(
      ///绑定stream
      stream: viewModel.streamController.stream,
      ///默认的数据
      initialData: viewModel.count.toString(),
      ///构建绑定数据的UI
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        ///snapshot.data 就是传递的数据对象
        return Text(
          '当前值  ${snapshot.data} ',
          style: const TextStyle(fontSize: 22, color: Colors.blue),
        );
      },
    );
  }
}

2在PageOne,pageTwo中,添加出发监听;并监听Count值的变化

你可能感兴趣的:(flutter,android,android,studio)