Flutter: call a method from another class / setState a page from outside that class with StreamController

This Flutter demo shows how to call a method from another class or how to setState a page from outside that class, using StreamController.





main.dart

import 'package:flutter/material.dart';
import 'dart:async';

StreamController<int> streamController = StreamController<int>();

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage('Flutter Demo Home Page', streamController.stream),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage(this.title, this.stream);
final String title;
final Stream<int> stream;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
String menuName = 'A';

@override
void initState() {
super.initState();
widget.stream.listen((index) {
mySetState(index);
});
}

void mySetState(int index) {
List menuList = ['A', 'B', 'C'];
setState(() {
menuName = menuList[index];
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(30.0),
child: Text(
'Today\'s special is:',
style: TextStyle(fontSize: 20),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'Combo ' + menuName,
style: TextStyle(fontSize: 30, color: Colors.blue),
),
),
SizedBox(
height: 50,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(Colors.blue[700]),
),
child: Text(
'Settings',
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
),
],
),
),
);
}
}

class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
List<bool> isSelected = [true, false, false];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(30.0),
child: Text(
'Select a menu name:',
style: TextStyle(fontSize: 20),
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: ToggleButtons(
children: <Widget>[
Text('A'),
Text('B'),
Text('C'),
],
onPressed: (int index) {
setState(() {
for (int buttonIndex = 0;
buttonIndex < isSelected.length;
buttonIndex++) {
if (buttonIndex == index) {
isSelected[buttonIndex] = true;
} else {
isSelected[buttonIndex] = false;
}
}
});
streamController.add(index);
},
isSelected: isSelected,
),
),
],
),
),
);
}
}


Comments

Popular posts from this blog

Android CameraX Picture And Video Capture Complete Code Tutorial

How To Add AdMob To Flutter App Quick Tutorial