How can i create a button that when user click on the button, the page will refresh and show new content?
Call the setState(() {}) method. You need a StatefulWidget for that.
Your code will be something like
RaisedButton(
child : Text("Tap"),
onPressed : () {
setState(() {
// modifiy the state
})
}
),
Here is a Codepen example of the code below
class _MyWidgetState extends State<MyWidget> {
int counter = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
counter++;
});
},
child: Text(
"Flat Button",
),
),
Text(
'Counter',
style: Theme.of(context).textTheme.headline4,
),
Text(
'$counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}
Related
i have the following simple full code
import 'dart:developer';
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
#override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
List myListWidget = [];
late bool isColorWhie = false;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
setState(() {
myListWidget.add(
Container(
width: 50,
height: 50,
color: isColorWhie?Colors.white:Colors.red,
)
);
});
},
child: Scaffold(
backgroundColor: Colors.green,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...myListWidget,
TextButton(
onPressed: (){
setState(() {
isColorWhie = !isColorWhie; // here never update
log('done');
});
},
child: const Text('tab to Change color',style: TextStyle(color: Colors.white),)
)
],
),
),
),
);
}
}
i tap on any point on screen to add Container into myListWidget thn call setState(() {}); to update ui.
everything fine now but when i change the isColorWhie to true it should change the color to white but it never update !
i am totally confused why it does not update ? And how could i handle with this ?
For base color change, I am using a separate button, also switching the list value.
One thing variable does update the UI, you need to handle state inside the item(state-management property) or reinitialize the variable to get update state.
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
#override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
List<bool> myListWidgetState = [];
bool isColorWhie = false;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(
() {
myListWidgetState.add(isColorWhie);
},
);
},
child: Scaffold(
backgroundColor: Colors.green,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...myListWidgetState.map(
(e) {
return Container(
width: 50,
height: 50,
color: e ? Colors.white : Colors.red,
);
},
),
TextButton(
onPressed: () {
myListWidgetState = myListWidgetState.map((e) => !e).toList();
setState(() {});
print(isColorWhie);
},
child: const Text(
'tab to Change color',
style: TextStyle(color: Colors.white),
),
),
TextButton(
onPressed: () {
setState(() {
isColorWhie = !isColorWhie;
});
print(isColorWhie);
},
child: const Text(
'tab to Change base color',
style: TextStyle(color: Colors.white),
),
),
],
),
),
),
);
}
}
Since you create a container as an object in GestureDetector and save it to your list, it will not change. It is now permanently saved (of course as long as you do not delete the element) as an entry in your list.
Your logic works exactly as you programmed it. For example, if you were to recompile the app and press the TextButton and then anywhere on your screen, a white container would also appear.
If you want to dynamically change the color of all containers at once, then you can do the following:
class _TestState extends State<Test> {
int containerCounter = 0;
late bool isColorWhie = false;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
containerCounter++;
});
},
child: Scaffold(
backgroundColor: Colors.green,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 50,
child: ListView.builder(
shrinkWrap: true,
itemCount: containerCounter,
itemBuilder: ((context, index) {
return Container(
height: 50,
color: isColorWhie ? Colors.white : Colors.red,
);
}),
),
),
TextButton(
onPressed: () {
setState(() {
isColorWhie = !isColorWhie; // here never update
});
},
child: const Text(
'tab to Change color',
style: TextStyle(color: Colors.white),
))
],
),
),
),
);
}
}
My goal is to display certain widgets based on clicks in a menu.
What I need when I click a title, is to shows a certain widget.
Here is the full code:
class SideMenu extends StatelessWidget {
const SideMenu({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Drawer(
child: SingleChildScrollView(
// it enables scrolling
child: Column(
children: [
DrawerHeader(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: defaultPadding * 3,
),
Image.asset(
"assets/logo/logo_icon.png",
scale: 5,
),
SizedBox(
height: defaultPadding,
),
Text("Récolt"),
],
)),
DrawerListTile(
title: "Tableau de bord",
svgSrc: "assets/icons/menu_dashbord.svg",
press: () {},
),
DrawerListTile(
title: "Utilisateurs",
svgSrc: "assets/icons/menu_profile.svg",
press: () {},
),
DrawerListTile(
title: "Collaborateurs",
svgSrc: "assets/icons/menu_doc.svg",
press: () {},
),
DrawerListTile(
title: "Producteurs",
svgSrc: "assets/icons/menu_store.svg",
press: () {},
),
DrawerListTile(
title: "Paramètres",
svgSrc: "assets/icons/menu_setting.svg",
press: () {},
),
],
),
),
);
}
}
I've got a extern page for display my widget like this :
SizedBox(height: defaultPadding),
ListUserEntreprise(),
SizedBox(height: defaultPadding),
ListUserCollab(),
I don't know how to do it, I tried with using a boolean in onPressed but it didn't work, I don't know really how to declare it and use it with an external page. Can someone help me, please?
use StatefulWidget and try with a boolean with the onPressed, setState() to update UI
Example:
import 'package:flutter/material.dart';
class SideMenu extends StatefulWidget {
const SideMenu({
Key? key,
}) : super(key: key);
#override
State<SideMenu> createState() => _SideMenuState();
}
class _SideMenuState extends State<SideMenu> {
bool _isShow = false;
#override
Widget build(BuildContext context) {
return Drawer(
child: SingleChildScrollView(
// it enables scrolling
child: Column(
children: [
DrawerListTile(
title: "Tableau de bord",
svgSrc: "assets/icons/menu_dashbord.svg",
press: () {
setState(() {
_isShow = !_isShow;
});
},
),
Visibility(
visible: _isShow,
child: Container(
child: Text('Tableau de bord'),
))
],
),
),
);
}
}
Im trying to make it so when you press search it creates a listtile. It works but for it to work I have to click the button and then rebuild the app for it to appear. I was looking at some other posts but I could not find anything that worked. The main parts to look at is I have a function that adds a listtile. I have a button with an on press to create the tile. And I have the children of container at the bottom as the list of created listtiles.
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Widget> _listOfWidgets = [];
#override
Widget build(BuildContext context) {
_addItemToList() {
List<Widget> tempList =
_listOfWidgets; // defining a new temporary list which will be equal to our other list
tempList.add(ListTile(
key: UniqueKey(),
leading: Icon(Icons.list),
trailing: FlatButton(
onPressed: () async {},
//Download Link
child: Text(
"Download",
style: TextStyle(color: Colors.green, fontSize: 15),
),
),
title: Text("")));
this.setState(() {
_listOfWidgets =
tempList; // this will trigger a rebuild of the ENTIRE widget, therefore adding our new item to the list!
});
}
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: currentTheme.currentTheme(),
home: Scaffold(
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
setState(() {
currentTheme.switchTheme();
});
},
icon: Icon(Icons.wb_sunny),
),
IconButton(
onPressed: () async {
await FirebaseAuth.instance.signOut();
},
icon: Icon(Icons.exit_to_app),
),
],
backgroundColor: Colors.blue,
title: Text("Home"),
),
body: ListView(
children: [
ListTile(
leading: SizedBox(
width: 300,
child: TextField(
controller: search,
decoration: InputDecoration(
labelText: "Enter Manga Name",
),
),
),
trailing: ElevatedButton(
onPressed: () async {
_addItemToList();
},
child: Text("Search")),
),
Container(
margin: EdgeInsets.all(15),
width: 100,
height: 515,
color: Colors.black12,
child: ListView(
children: _listOfWidgets,
))
],
)));
}
}
try add below code
if you update status you need setState()
A better way to state management is to use a BLoC or Provider package.
...
onPressed: () {
setState(() {
_addItemToList();
});
},
...
Figured it out after a bit of tinkering. Fix for me was to add key: UniqueKey(), to my ListView. I had keys added to my ListTiles instead of the actual ListView.
onPressed: () {
setState(() {
_addItemToList();
});
},
The Problem Solution is :
List<Widget> tempList = <Widget>[];
_addItemToList() {
tempList.addAll(
_listOfWidgets); // defining a new temporary list which will be equal to our other list
tempList.add(ListTile(
key: UniqueKey(),
leading: Icon(Icons.list),
trailing: FlatButton(
onPressed: () async {},
//Download Link
child: Text(
"Download",
style: TextStyle(color: Colors.green, fontSize: 15),
),
),
title: Text("")));
this.setState(() {
_listOfWidgets =
tempList; // this will trigger a rebuild of the ENTIRE widget, therefore adding our new item to the list!
});
}
This is my first time on flutter framework and Dart programming I have so manny miss of understanding Dart language.
I want to hide onStepContinue button for the last step and onStepCancel for the first step on flutter? this is my code I'm newbe in flutter any help?
class _MyHomePageState extends State<MyHomePage> {
int _currentStep = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Stepper(
controlsBuilder: (BuildContext context, ControlsDetails details) {
return Row(
children: <Widget>[
TextButton(
onPressed: details.onStepContinue,
child: const Text('NEXT'),
),
TextButton(
onPressed: details.onStepCancel,
child: const Text('BACK'),
),
],
);
},
steps: const [
Step(
title: Text("Step 1"),
content: Text("Information for step 1"),
),
Step(
title: Text("Step 2"),
content: Text("Information for step 2"),
),
Step(
title: Text("Step 3"),
content: Text("Information for step 3"),
),
],
onStepTapped: (int newIndex){
setState(() {
_currentStep = newIndex;
});
},
currentStep: _currentStep,
onStepContinue: () {
if (_currentStep != 2) {
setState(() {
_currentStep += 1;
});
}
},
onStepCancel: () {
if (_currentStep != 0) {
setState(() {
_currentStep -= 1;
});
}
},
),
),
);
}
}
Use conditional state to show the buttons.
controlsBuilder: (BuildContext context, ControlsDetails details) {
return Row(
children: <Widget>[
if (_currentStep != 2) // skip on last step
TextButton(
onPressed: details.onStepContinue,
child: const Text('NEXT'),
),
if (_currentStep != 0)// skip on 1st step
TextButton(
onPressed: details.onStepCancel,
child: const Text('BACK'),
),
],
);
},
Wrap your widget using Visibility like this,
bool goneVisibilty=true;
Visibility(
child: Text("Gone"),//replace with your widget
visible: goneVisibility,
),
when ever u need to update this widget call setState to update.
setState((){
goneVisibility=false;
});
To Enable/Disable Button you can use this
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _isButtonDisabled;
#override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
Is anyone know how to change a text style on Flutter when the button pressed?
As example, i have a code like this :
class _scanningState extends State<scan> {
String strText = 'ABCDEFG';
#override
Widget build(BuildContext context) {
return Scaffold(backgroundColor: Colors.blue,
body: new Column(
children: <Widget>[
new Text(strText),
new RaisedButton(
child: new Text('Button'),
onPressed: (){
//Change text style of strText()???
},
)
],
)
);
}
class _scanningState extends State<scanning> {
bool pressed = true;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue,
body: new Column(
children: <Widget>[
new Text(strText,
style: pressed
? TextStyle(color: Colors.black)
: TextStyle(color:Colors.green),
),
new RaisedButton(
child: new Text(
'Change color'),
onPressed: () {
setState(() {
pressed = !pressed;
});
},
)
],
));
}
Maybe you want to change the sibling text. The concept is the same. Happy Flutter
I recommend you to read about Stateful Widgets https://flutter.io/tutorials/interactive/#stateful-stateless
class _scanningState extends State<scanning> {
bool pressed = false;
String strText = 'ABCDEFG';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue,
body: new Column(
children: <Widget>[
new Text(strText),
new RaisedButton(
child: new Text(
'Button',
style: pressed
? TextStyle(fontSize: 30.0)
: TextStyle(fontSize: 10.0),
),
onPressed: () {
//Change text style of strText()???
setState(() {
pressed = !pressed;
});
},
)
],
));
}