Flutter: Button should output an widget but doesn't - flutter

This is my function:
Widget RandomSkill(Widget SkillJonglieren) {
return Widget SkillJonglieren;
This is the stateless Widget "SkillJonglierten"
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Column(
children: <Widget>[
Text('Jonglieren'),
Image.asset('images/Jonglieren.jpg')
],
),
),
);
}
}
This is the button
body: Align(alignment: Alignment.bottomCenter,
child: RaisedButton(
onPressed: RandomSkill,
child: Text('Zufälliger Skill')
),
));
I just want, that when i press the button that this widget is shown

You need a StatefulWidget. In its State class, you need to remember whether the SkillJonglierten is shown or not. If it's shown, you need to show it in your build() function. Otherwise, you should not show it in your build() function. So, this becomes: https://codepen.io/gazialankus/pen/rNxgBgx
class _MyHomePageState extends State<MyHomePage> {
bool isShown;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('Show'),
onPressed: () {
setState(() {
isShown = true;
});
}
),
if (isShown == true) SkillJonglieren()
],
),
),
);
}
}

Related

Add new widget upon clicking floating action button in flutter

I am a beginner in Flutter. I am trying to add a new list item widget to screen when floating action button is pressed. How do I achieve this?
I am trying to create a list of items. When the floating action button is clicked, a dialog box is prompted and user is asked to enter details. I want to add a new list item with these user input details.
This is my input_page.dart file which I am calling in main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MedPage extends StatefulWidget {
#override
_MedPageState createState()=> _MedPageState();
}
class _MedPageState extends State<MedPage> {
Future<String>createAlertDialog(BuildContext context) async{
TextEditingController customController= new TextEditingController();
return await showDialog(context: context,builder: (context) {
return AlertDialog(
title: Text("Name of the Pill"),
content: TextField(
controller: customController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: (){
Navigator.of(context).pop(customController.text.toString()); // to go back to screen after submitting
}
)
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My med app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
Expanded(
child: ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
ReusableListItem(Color(0xFFd2fddf),"Name 1"),
ReusableListItem(Colors.orange,"Name 2"),
ReusableListItem(Color(0xFF57a1ab), "Name 3"),
],
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
print("Clicked");
createAlertDialog(context).then((onValue){
print(onValue);
setState(() {
});
});
},
child: Icon(Icons.add),
),
);
}
}
class ReusableListItem extends StatelessWidget {
ReusableListItem(this.colour,this.pill);
Color colour;
String pill;
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: colour,
borderRadius: BorderRadius.circular(15.0)
),
child: Center(
child: Text(pill)
),
);
}
}
You don't need to change much in your code, maintain a variable that stores the values entered to be able to show them in the list. You should use Listview.builder() in order to dynamically render the items.
Here's your code:
class MedPage extends StatefulWidget {
#override
_MedPageState createState() => _MedPageState();
}
class _MedPageState extends State<MedPage> {
List<String> items = [];
Future<String> createAlertDialog(BuildContext context) async {
TextEditingController customController = new TextEditingController();
return await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Name of the Pill"),
content: TextField(
controller: customController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(customController.text
.toString()); // to go back to screen after submitting
})
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My med app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return ReusableListItem(Color(0xFFd2fddf), items[index]);
},
itemCount: items.length,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print("Clicked");
createAlertDialog(context).then((onValue) {
// print(onValue);
setState(() {
items.add(onValue);
});
});
},
child: Icon(Icons.add),
),
);
}
}
class ReusableListItem extends StatelessWidget {
ReusableListItem(this.colour, this.pill);
final Color colour;
final String pill;
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: const EdgeInsets.all(8),
decoration:
BoxDecoration(color: colour, borderRadius: BorderRadius.circular(15.0)),
child: Center(child: Text(pill)),
);
}
}
Firstly you need to use ListView.builder() rather than ListView because you have dynamic content. Also you need to hold your items in a list.
// create a list before
ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Text(list[index]);
}
)
When you click on FloatingActionButton() you will call AlertDialog() method.
FloatingActionButton(
onPressed: (){
AlertDialog(
content: Form(), // create your form here
actions: [
// add a button here
]
)
})
This method will show a dialog(you will add a form inside of the dialog). When the user completes the form(after clicking the button) you will add a new object to the list and update the state with setState({})
onPressed: (){
setState({
// add new object to the list here
});
Navigator.pop(context); // this will close the dialog
}

setState not updating

I just can't figure out what is the problem with this set state method in flutter. Everything seems okay. But the text is not updating on onPressed.
class NetBalanceWidget extends StatefulWidget {
#override
_NetBalanceWidgetState createState() => _NetBalanceWidgetState();
}
class _NetBalanceWidgetState extends State<NetBalanceWidget> {
#override
Widget build(BuildContext context) {
String text = 'NetBalance-Amount';
return RawMaterialButton(
onPressed: () {
setState(() {
text = 'It works';
});
},
child: Container(
height: 80.0,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(text),
Text('0.00'),
],
),
),
),
);
}
}
You have text as a local variable in the build method. setState is essentially just calling build again, and is resetting the value of text back to its default of 'NetBalance-Amount'.
Move its declaration outside of build:
class _NetBalanceWidgetState extends State<NetBalanceWidget> {
String text = 'NetBalance-Amount';
#override
Widget build(BuildContext context) {
return RawMaterialButton(
onPressed: () {
setState(() {
text = 'It works';
});
},
child: Container(
height: 80.0,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(text),
Text('0.00'),
],
),
),
),
);
}
}

Flutter - Is it possible to show a snackbar inside another Container than the one used to trigger .show?

Is it possible to have the snackbar appearing only in another widget?
I am trying something like that so that when we click on the button the snackbar would only be embedded inside the Container, not appearing outside of it but it is not working:
#override
Widget build(BuildContext context) {
BuildContext snackContext;
return Stack(
children: [
Builder(builder: (BuildContext context) {
snackContext = context;
return Container(height: 300, width: 300, child: Text('Test'));
}),
TextButton(
onPressed: () {
ScaffoldMessenger.of(snackContext).showSnackBar(
SnackBar(
backgroundColor: Color(0x44000000),
content: Text(
'Test of snackbar',
),
),
);
},
)
],
);
}
Please advise~
Save the correct context in the State. This code works for me:
class _TestPageState extends State<TestPage> with TickerProviderStateMixin {
BuildContext snackContext;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 300,
width: 200,
child: Scaffold(
backgroundColor: Colors.deepPurple,
body: Builder(builder: (BuildContext context) {
snackContext = context;
return Container(height: 300, width: 300, child: Text('Test'));
}),
),
),
Center(
child: TextButton(
onPressed: () {
Scaffold.of(snackContext).showSnackBar(
SnackBar(
backgroundColor: Color(0x44000000),
content: Text(
'Test of snackbar',
),
),
);
},
child: Text('data'),
),
)
],
),
);
}
}
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}

Flutter ListView/ListTiles are not rendering on the page

I am new to Flutter/Dart but I am trying to incorporate a ListView into a project that I am working on but I cannot get it to work. I have tried it at least 12 different ways and it is still not working. I know the issue has something to do with the way I am sizing (or not sizing) the ListView/ListTiles. I have tried adding heights to SizedBoxes, heights to Containers, widths to columns, Expanded, Flexible etc. Nothing has worked. I am not posting the error messages because with all of the solutions I have tried they have all essentially been related to either the height or width of the ListView/ListTile exceeding the limitations of the screen. Below are the latest code snippet I have tried. I know there are several topics on SO that have addressed this but I have not been able to get any of them to work. My ListView should only contain 3 tiles so perhaps a ListView.Builder would be better. I am open to any suggestions or advice. Thanks in advance for the help!
class _HotelFormState extends State<HotelForm> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hotel Form'),
),
body: Column(
children: <Widget>[
SizedBox(height: 20.0),
Row(
children: <Widget>[
TripDates(),
],
),
SizedBox(height: 20.0),
Column(
children: <Widget>[
RoomCounts(),
],
),
],
),
);
}
}
RoomCounts Class
class RoomCounts extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
height: 100.0,
child: new ListView(
children: new List.generate(3, (i) => new ListTileItem(title: "$i",)),
),
),
);
}
}
ListTile Class
class _ListTileItemState extends State<ListTileItem> {
//Some lists are here
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Flexible(
child: ListTile(
leading: Icon(widget.icons),
title: new Text(widget.title),
trailing: new Row(
children: <Widget>[
_itemCount != 0
? new IconButton(icon: new Icon(Icons.remove), onPressed: () => setState(() => _itemCount--),)
: new Container(),
new Text(_itemCount.toString()),
new IconButton(icon: new Icon(Icons.add), onPressed: () => setState(() => _itemCount++))
],
),
),
),
],
);
}
}
You can copy paste run full code below
You do not need Scaffold in RoomCounts
You do not need Column in _ListTileItemState
You need SizedBox in trailing of ListTile
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HotelForm(),
);
}
}
class HotelForm extends StatefulWidget {
#override
_HotelFormState createState() => _HotelFormState();
}
class _HotelFormState extends State<HotelForm> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hotel Form'),
),
body: Column(
children: <Widget>[
SizedBox(height: 20.0),
/*Row(
children: <Widget>[
TripDates(),
],
),*/
SizedBox(height: 20.0),
Column(
children: <Widget>[
RoomCounts(),
],
),
],
),
);
}
}
class RoomCounts extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 100.0,
child: ListView(
children: List.generate(
3,
(i) => ListTileItem(
title: "$i",
)),
),
);
}
}
class ListTileItem extends StatefulWidget {
final String title;
final IconData icons;
ListTileItem({this.title, this.icons});
#override
_ListTileItemState createState() => _ListTileItemState();
}
class _ListTileItemState extends State<ListTileItem> {
int _itemCount = 0;
#override
Widget build(BuildContext context) {
return ListTile(
leading: Icon(widget.icons),
title: Text(widget.title),
trailing: SizedBox(
width: 200,
child: Row(
children: <Widget>[
_itemCount != 0
? IconButton(
icon: Icon(Icons.remove),
onPressed: () => setState(() => _itemCount--),
)
: Container(),
Text(_itemCount.toString()),
IconButton(
icon: Icon(Icons.add),
onPressed: () => setState(() => _itemCount++))
],
),
),
);
}
}

Determine Scroll Widget height

I would like to determine if a 'scrollable' widget indeed needs to scroll. I would ultimately like to show something like 'Scroll for more'. How do I achieve this?
I could use a combination of LayoutBuilder and a ScrollController. However, ScrollController gives me maxScrollExtent and minScrollExtent only after any event - like say for example user trying to scroll
I would like to know during 'build' so that I can determine to show 'Scroll for more' or not depending on the screen dimensions
class _MyHomePageState extends State<MyHomePage> {
int value = 0;
String text = 'You have pushed the button 0 times\n';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 9,
child: SingleChildScrollView(
child: Text(text),
),
),
Expanded(
flex: 1,
child: Text('Scroll for more')),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
value += 1;
text = text + 'You have pushed the button $value times \n';
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
I would like to dynamically display
Text('Scroll for more'),
only if the SingleChildScrollView needs to be scrolled to view the entire content. Please note, I am just giving the above code as example.
In my real case, I have a StreamBuilder inside a SingleChildScrollView and I cannot determine how much of data is going to be flowing in from the stream. I also do not have any button or tap or any gesture to access the controller and setState
Thanks in advance for any help
class _MyHomePageState extends State<MyHomePage> {
bool showMore = false;
final scrollController = ScrollController();
#override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback((_) {
setState(() {
showMore = scrollController.position.maxScrollExtent > 0;
});
});
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 9,
child: SingleChildScrollView(
controller: scrollController,
child: SizedBox(height: 650, child: Text('blah')),
),
),
if (showMore) Expanded(flex: 1, child: Text('Scroll for more')),
],
),
),
);
}
}