如何从另一个类中调用方法或者使用StreamController从该类外部setState页面。
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,
),
),
],
),
),
);
}
}
context.ancestorStateOfType
。 - Rémi RousseletStreamController
传递给子代,而不仅仅是Stream
,如果您的子代应该提交事件。 - Rémi Rousselet