1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Use stream in provider with flutter

Discussão em 'Mobile' iniciado por Stack, Novembro 5, 2024 às 11:12.

  1. Stack

    Stack Membro Participativo

    I make a simple example to understand using Stream with Provider pattern in flutter.

    I do not know How can I change stream value in this case ? - when I click Add icon, the value will be add, count value is increased (like Sink.add)

    Please help me understand using Stream with Provider.

    Thanks a lot!!!

    Screen:

    [​IMG]

    this is my code:

    import 'dart:async';
    import 'dart:convert';

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:provider/provider.dart';

    // Main app and Pages for Tab Layout
    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
    primarySwatch: Colors.blue,
    ),
    home: MultiProvider(
    providers: [
    StreamProvider(
    create: (_) => EventProvider().intStream(), initialData: 0),
    ],
    child: DefaultTabController(
    length: 1,
    child: DefaultTabController(
    length: 1,
    child: Scaffold(
    appBar: AppBar(
    title: Text("Provider Demo"),
    bottom: TabBar(
    tabs: [
    Tab(icon: Icon(Icons.add)),
    ],
    ),
    ),
    body: TabBarView(
    children: [
    MyEventPage(),
    ],
    ),
    ),
    ))));
    }
    }

    // Event page (counting)
    class MyEventPage extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    var _value = Provider.of<int>(context);
    return Container(
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
    Center(
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
    Text('StreamProvider Example'),
    SizedBox(height: 50),
    Text('${_value.toString()}',
    style: Theme.of(context).textTheme.display1)
    ],
    )),
    Align(
    alignment: Alignment.bottomRight,
    child: RaisedButton(
    onPressed: () {
    EventProvider().add();
    },
    child: Icon(Icons.add),
    ),
    )
    ],
    ));
    }
    }

    // User List Page

    // EventProvider (Stream)
    class EventProvider {
    StreamController<int> sc = StreamController();
    int count = 0;

    Stream<int> intStream() {
    // return Stream<int>.periodic(interval, (int _count) => _count++);
    return sc.stream;
    }

    add () {
    count++;
    sc.sink.add;
    }
    }

    Continue reading...

Compartilhe esta Página