Using Stream/Sink in Flutter

前端 未结 3 940
半阙折子戏
半阙折子戏 2021-02-10 11:22

I\'m trying to replace the increment flutter app code, by using Streams from Dart API without using scoped_model or rxdart.

So I read this and watched this,

3条回答
  •  故里飘歌
    2021-02-10 11:51

    A simple implementation

    import 'dart:async';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Counter Demo',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      int _counter = 0;
    
      final StreamController _streamController =
          StreamController.broadcast();
    
      Stream get _stream => _streamController.stream;
    
      void increamentCounter() {
        _counter++;
        _streamController.add(_counter);
    
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter demo'),
          ),
          body: Center(
            child: StreamBuilder(
                stream: _stream,
                builder: (ctxt, snapshot) {
                  if (snapshot.hasData) {
                    return Text(
                        'You have pushed this button ${snapshot.data} times');
                  }
                  return Text('You have pushed this button ${0} times');
                }),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              increamentCounter();
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

提交回复
热议问题