I want to write an ui as below:
the main feature is when click the button ,a new random position Text will be created inside the red box, the problem I faced is when I click the button ,a randon position Text widget will be create,but the old Text was gone, anyone can help me ? following is my code:
class AddNewWidget extends StatefulWidget {
const AddNewWidget({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _AddNewWidgetState();
}
class _AddNewWidgetState extends State<AddNewWidget> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: const Text("Add Text"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Add Text Below:'),
Stack(
children: [
Container(
width: double.infinity,
height: 600,
decoration: BoxDecoration(
border: Border.all(width: 2.0, color: Colors.red),
),
),
_addText(),
],
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _press,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
_press() {
//print("_press");
setState(() {});
}
_addText() {
return Positioned(
child: Text(
"hello ${Random().nextInt(10)}",
key: ValueKey(Random().nextInt(100)),
),
left: (Random().nextInt(300)).toDouble(),
top: (Random().nextInt(600)).toDouble(),
);`enter code here`
}
}
CodePudding user response:
Create list to hold the generated item and then show the list on stack like
class AddNewWidget extends StatefulWidget {
const AddNewWidget({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _AddNewWidgetState();
}
class _AddNewWidgetState extends State<AddNewWidget> {
List<Widget> items = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Add Text"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Add Text Below:'),
Expanded(
child: Stack(
children: [
Container(
height: 600,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: Colors.red,
),
),
),
...items.map((e) => e).toList()
],
),
),
FloatingActionButton(
onPressed: _press,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _press,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
_press() {
items.add(_addText());
setState(() {});
}
Widget _addText() {
return Positioned(
child: Text(
"hello ${Random().nextInt(10)}",
key: ValueKey(Random().nextInt(100)),
),
left: (Random().nextInt(300)).toDouble(),
top: (Random().nextInt(600)).toDouble(),
);
}
}
include two fab, if you need to position any fab, place it within stack with Positioned(bottom:-20,righ:20)
, play with this value