问题
What I want to achieve is explained below:- To show several widgets by clicking a button. The dynamically displayed widgets are basically FlatButtons with Icons as child. So when I click these buttons, I want the icon to change. However, on testing it - I found that their state doesn't change. Below is a sample code
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
IconData icon;
List<Widget> w;
void initState() {
super.initState();
w = List();
}
Widget getWidget() {
icon = Icons.play_arrow;
return Center(
child: FlatButton(
child: Icon(
icon,
color: Colors.black,
),
onPressed: () {
setState(() {
icon = Icons.pause;
});
},
)
);
}
@override
Widget build(BuildContext context) {
//w = Widget();
return Scaffold(
appBar: AppBar(
title: Text('Speech Aid'),
),
body: Column(
children: <Widget>[
Center(
child: FlatButton(
child: Text('Text'),
onPressed: () {
setState(() {
List<Widget> w1 = List();
w1.add(getWidget());
w = w1;
});
},
)
),
...w,
],
),
);
}
}
回答1:
This may help you
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Test(),
);
}
}
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
List<Widget> playButtonList;
void initState() {
playButtonList = <Widget>[];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Speech Aid'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
FlatButton(
child: Text('Add Play Button'),
color: Colors.black26,
onPressed: () {
setState(() {
playButtonList.add(PlayButton());
});
},
),
Expanded(
child: ListView.builder(
itemCount: playButtonList.length,
itemBuilder: (context, index) => playButtonList[index],
),
)
],
),
);
}
}
class PlayButton extends StatefulWidget {
@override
_PlayButtonState createState() => _PlayButtonState();
}
class _PlayButtonState extends State<PlayButton> {
IconData icon;
@override
void initState() {
icon = Icons.play_arrow;
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
child: Icon(icon),
onPressed: () {
setState(() {
if (icon == Icons.play_arrow)
icon = Icons.pause;
else
icon = Icons.play_arrow;
});
},
),
);
}
}
来源:https://stackoverflow.com/questions/59429223/flutter-dynamically-adding-widget-that-needs-to-change-state-as-well