Search code examples
flutterstream-builder

Send data from several pages to StreamController on Home and listen on Home page


I am working on a shopping application. I have not been able to solve this problem for days. I want to send information from the other pages to the StreamController on the Main page and listen to it on the Main. But I can't. I can easily send and listen to information from the main page. I can't do that from the second and third pages. There are similar questions in StackOverflow, but they all use Constructor. This method allows you to use between two pages. I want to send information to Stream from a few pages and listen. (Example: I want to throw a product into the cart from the Home page, product details page, My Wishlists, etc. pages, and make sure that these products appear in the Cart when I go to the Cart page.) I believe I was able to express my opinion correctly. I hope I find a solution. Thank you for your attention and answers.

I share a similar code below.

stream.dart

import 'package:flutter/material.dart';

class MyStream {
  StreamController controller = StreamController();

  String setNum(String data) {
    controller.sink.add(data);
    debugPrint("Count $data");
    return data;
  }
}

main.dart

class MainApp extends StatefulWidget {
  const MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => MainAppState();
}

class MainAppState extends State<MainApp> {
  String streamNum = "0";
  MyStream streamNumber = MyStream();

  @override
  void initState() {
    streamNumber.controller.stream.listen((event) {
      setState(() {
        streamNum = event;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            streamNum,
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () {
                    /* String int = (1 + Random().nextInt(20)).toString();
                checkNum.check(int); */  //When this Part is active, the program runs properly within the main
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (BuildContext context) =>
                                const SecondPage()));
                  },
                  child: const Text("Second Page")),
              const SizedBox(
                width: 20,
              ),
              ElevatedButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (BuildContext context) =>
                                const ThirdPage()));
                  },
                  child: const Text("Third Page"))
            ],
          )
        ],
      ),
    ));
  }
}

second.dart

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () {
                    String num = Random().nextInt(20).toString();
                    MainAppState().streamNumber.controller.add(num);
                  },
                  child: const Text("Add Stream to Main Page"))
            ],
          ),
        ));
  }
}

third.dart

class _ThirdPageState extends State<ThirdPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () {
                    String num = Random().nextInt(20).toString();
                    MainAppState().streamNumber.controller.sink.add(num);
                  },
                  child: const Text("Add Stream to Main Page"))
            ],
          ),
        ));
  }
}

Solution

  • You need to use a good state management, i recommend using https://pub.dev/packages/provider