How To Create Nest Stream Builder Using Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 02-11-2020

One of the interesting things about Flutter is, in contrast to Android JVM, it blurs the line between Activity. Fragment and Views. Any time, you would need to display something to user, you are to provide a Widget. Those widgets can be nested into other widgets (just like views). The widgets care about visible elements only, which works nicely with architectures like MVI/MVP. If we use reactive streams, and provide all UI updates, the widgets play nicely with them.

How To Create Nest Stream Builder Using Flutter Android App

Nest Stream Builder
Complete Code For Nest Stream Builder In Flutter
main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Stream<int> timedCounter(Duration interval, [int maxCount]) async* {
    int i = 0;
    while (true) {
      await Future.delayed(interval);
      yield i++;
      if (i == maxCount) break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
        appBar: AppBar(
            backgroundColor: Colors.pink[800],
            title: Text("Nest Stream Builder"
            )),
      body: Center(
        child: StreamBuilder<int>(
          stream: timedCounter(Duration(seconds: 2), 40),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text("No data");
            }
            int firstCount = snapshot.data;
            return StreamBuilder(
                stream: timedCounter(Duration(seconds: 1), 45),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Text("No data");
                  }
                  int secondCount = snapshot.data;
                  return Text(
                      "First Count: $firstCount, Second Count: $secondCount",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.lightGreen
                      ));
                });
          },
        ),
      ),
    );
  }
}

Related Post