How to call setState in a widget to change that widget with other one? - flutter

I have 2 widget and I put the first one into a variable. When I click a button in the first widget, I will call setState and put the second widget to the variable to rebuild. However, it didn't work.
I try to call setState in the parent widget of them and it work. Anyone know what wrong with it and how to solve this?
This is my code:
Widget checkinWidget = CheckInTemplate();
Column(
children: <Widget>[
Expanded(
flex: 3,
child: Container(),
),
Expanded(
flex: 1,
child: AnimatedSwitcher(
duration: const Duration(seconds: 1),
child: checkinWidget
),
)
],
),
I put the first widget CheckInTemplate to a variable and in CheckInTemplate, I have a button:
RaisedButton(
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 60),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)
),
color: Colors.white,
onPressed: (){
setState(() {
checkinWidget = CaptureCameraTemplate();
});
},
child: Text('Check in',
style: TextStyle(
fontSize: 25,
fontFamily: 'FredokaOne'
),),
),
When I click the button, nothing happen.

I developed one example for this, kindly check the below 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: 'Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WidgetHandling(),
);
}
}
class WidgetHandling extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _WidgetHandling();
}
}
class _WidgetHandling extends State<WidgetHandling> {
Widget widgetHolder;
void initState() {
widgetHolder = firstWidget();
super.initState();
}
Widget firstWidget() {
return Container(
color: Colors.white,
child: Center(
child: FlatButton(
color: Colors.blue,
textColor: Colors.white,
padding: EdgeInsets.all(8.0),
splashColor: Colors.blueAccent,
onPressed: () {
setState(() {
widgetHolder = secondWidget();
});
},
child: Text(
"First Widget",
style: TextStyle(fontSize: 20.0),
),
),
),
);
}
Widget secondWidget() {
return Container(
color: Colors.grey,
child: Center(
child: FlatButton(
color: Colors.blue,
textColor: Colors.white,
padding: EdgeInsets.all(8.0),
splashColor: Colors.blueAccent,
onPressed: () {
setState(() {
widgetHolder = firstWidget();
});
},
child: Text(
"Second Widget",
style: TextStyle(fontSize: 20.0),
),
),
),
);
}
#override
Widget build(BuildContext context) {
return widgetHolder;
}
}

You might have added this line,
Widget checkinWidget = CheckInTemplate();
in build method.
Remove it from build method and put to out side of build and then it will work.

Related

Open showModalBottomSheet from left side flutter

I am using ShowModalBottomSheet . I want to open it from left side not from bottom in flutter..
To achieve you desire UI requirements , you should create a custom modal sheet.
It is very simple , you just have to make a container and use tween animation to make it visible and it works like a modal sheet,You can change the direction of the container from its start animating and many more.
I will try to add a code for it later.
This package help you to achieve side modal sheet.
https://pub.dev/packages/side_sheet
Or there is one more way, you should visit this link,I hope it will fullfill your requirements.
https://pub.dev/packages/modal_side_sheet
I think the first package can be more helpfull for you because it has some customization options like you can choose the side etc.
in case someone still needs help. You can use a combination of overlay and Tween to create a custom side sheet.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Custom Sidesheet',
theme: ThemeData(useMaterial3: true),
home: const MyHomePage(title: 'Custom Sidesheet'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
OverlayEntry? sideSheetOverlayEntry;
final sideSheetOverlayLayerLink = LayerLink();
bool isSidebarShown = false;
#override
void initState() {
super.initState();
}
void showSideSheet() {
final sideSheetOverlay = Overlay.of(context)!;
sideSheetOverlayEntry = OverlayEntry(
builder: (context) => Positioned(
height: MediaQuery.of(context).size.height,
child: isSidebarShown
? CompositedTransformFollower(
link: sideSheetOverlayLayerLink,
child: TweenAnimationBuilder(
tween: Tween<double>(begin: 150, end: 300),
duration: const Duration(milliseconds: 300),
builder: (BuildContext context, double size, Widget? child) {
return Material(
child: SafeArea(
child: Container(
width: size,
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
InkWell(
onTap: () {
setState(() {
isSidebarShown = false;
showSideSheet();
});
},
onHover: (value) {},
child: const Icon(
Icons.close,
color: Colors.redAccent,
size: 25.0,
),
)
],
),
Column(
children: [
Container(
child: Text(
"Custom Side Sheet",
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: Colors.blueGrey),
),
),
const Divider(
height: 5.0,
color: Colors.black,
),
Container(
child: Row(children: [
Icon(
Icons.dashboard,
size: 25.0,
color: Colors.blueGrey,
),
Text(
"Home",
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.blueGrey, fontSize: 25.0, fontWeight: FontWeight.w300),
)
]),
)
],
)
],
)),
),
);
},
))
: SizedBox.shrink(),
),
);
sideSheetOverlay.insert(sideSheetOverlayEntry!);
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
leading: GestureDetector(
onTap: () {
setState(() {
isSidebarShown = true;
showSideSheet();
});
},
child: Icon(
Icons.menu_sharp,
size: 30.0,
),
),
),
body: Container(
color: Color.fromRGBO(223, 230, 233, 1.0),
)),
);
}
}
side sheet not active image
side sheet active image

Is there any way to put custom toolbar on the keypad?

I want to put a custom toolbar on the keypad like the image above. Is it possible in flutter? or should I write code on the iOS or Android side?
You can copy paste run full code below
Please see working demo below
You can use package https://pub.dev/packages/keyboard_overlay
Step 1: Use with HandleFocusNodesOverlayMixin
Step 2: Use FocusNodeOverlay for focusNode
Step 3: Use GetFocusNodeOverlay and set _focusNodeOverlay = GetFocusNodeOverlay(
Step 4: TextField use TextField(focusNode: _focusNodeOverlay,
code snippet
class _MyHomePageState extends State<MyHomePage>
with HandleFocusNodesOverlayMixin {
FocusNodeOverlay _focusNodeOverlay;
#override
void initState() {
_focusNodeOverlay = GetFocusNodeOverlay(
child: TopKeyboardUtil(
Container(
color: Colors.white,
height: 45,
width: MediaQueryData.fromWindow(ui.window).size.width,
child: Row(
children: [
GestureDetector(
child: Icon(Icons.save),
onTap: () => print("click"),
),
...
Spacer(),
Container(
width: 60,
child: Center(
child: DoneButtonIos(
backgroundColor: Colors.white,
textColor: Colors.green,
label: 'Post',
onSubmitted: () {
print("submit");
},
platforms: ['android', 'ios'],
),
),
),
],
),
),
),
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:keyboard_overlay/keyboard_overlay.dart';
import 'dart:ui' as ui;
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(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with HandleFocusNodesOverlayMixin {
FocusNodeOverlay _focusNodeOverlay;
#override
void initState() {
_focusNodeOverlay = GetFocusNodeOverlay(
child: TopKeyboardUtil(
Container(
color: Colors.white,
height: 45,
width: MediaQueryData.fromWindow(ui.window).size.width,
child: Row(
children: [
GestureDetector(
child: Icon(Icons.save),
onTap: () => print("click"),
),
GestureDetector(
child: Icon(Icons.computer),
onTap: () => print("click"),
),
GestureDetector(
child: Icon(Icons.home),
onTap: () => print("click"),
),
Spacer(),
Container(
width: 60,
child: Center(
child: DoneButtonIos(
backgroundColor: Colors.white,
textColor: Colors.green,
label: 'Post',
onSubmitted: () {
print("submit");
},
platforms: ['android', 'ios'],
),
),
),
],
),
),
),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
focusNode: _focusNodeOverlay,
style: TextStyle(color: Colors.grey),
decoration: InputDecoration(
labelText: 'Type Something',
labelStyle: TextStyle(color: Colors.black),
fillColor: Colors.orange,
hintStyle: TextStyle(
color: Colors.grey,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 1.0),
),
),
),
],
),
),
);
}
}
Yes there is a way around in the flutter to achieve this.
Create a widget of the toolbar you want to add.
Set it visible on input focus.
For reference I am sharing the code how I achieve that.
class InputDoneView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
color: Style.lightGrey,
child: Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(top: 1.0, bottom: 1.0),
child: CupertinoButton(
padding: EdgeInsets.only(right: 24.0, top: 2.0, bottom: 2.0),
onPressed: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Text(
"Done",
style: TextStyle(color: Style.primaryColor,fontWeight: FontWeight.normal)
),
),
),
),
);
}
}
To call this in your main view when input field is focused in and out.
showOverlay(BuildContext context) {
if (overlayEntry != null) return;
OverlayState overlayState = Overlay.of(context);
overlayEntry = OverlayEntry(builder: (context) {
return Positioned(
bottom: MediaQuery.of(context).viewInsets.bottom, right: 0.0, left: 0.0, child: InputDoneView());
});
overlayState.insert(overlayEntry);
}
removeOverlay() {
if (overlayEntry != null) {
overlayEntry.remove();
overlayEntry = null;
}
}

Show widget when button is clicked (Dart, Flutter)

how can I show a widget (for example some more buttons) when a button is clicked.
FlatButton(
onPressed: () {
//render the new widgets
},
child: Icon(
Icons.close,
color: Colors.white,
),
));
This is the parent class
class StopStream extends StatelessWidget
You can conditionally show / hide a widget(s) with a help of a variable.
You need a StatefulWidget to change the state of a widget i.e to dynamically show / hide (widgets).
Please see the following code, I use a bool showWidget to show or hide more FlatButton's in a Row :
import 'package:flutter/material.dart';
final Color darkBlue = const Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
bool showWidget = false;
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
showWidget
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
onPressed: () {},
child: const Icon(Icons.ac_unit),
),
FlatButton(
onPressed: () {},
child: const Icon(Icons.accessible),
),
FlatButton(
onPressed: () {},
child: const Icon(Icons.backpack),
),
FlatButton(
onPressed: () {},
child: const Icon(Icons.cached),
),
],
)
: Container(),
FlatButton(
onPressed: () {
setState(() {
showWidget = !showWidget;
});
},
child: const Icon(
Icons.close,
color: Colors.white,
),
),
],
);
}
}
Have a state variable (either in State or in something like Provider or Riverpod) that will be toggled by your onPressed: callback. Then allow that variable to control whether or not the widget in question is shown or omitted from the widget tree.
You can use a bool variable Forexample in my case isSwitched and set its value to false. When the user clicks on the button, set its value to true and use conditional operator to show more widgets as follows:
class CoverScreen extends StatefulWidget {
#override
_CoverScreenState createState() => _CoverScreenState();
}
class _CoverScreenState extends State<CoverScreen> {
bool isSwitched = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 70,
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
child: Text('WELCOME'),
),
],
)),
body: Padding(
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(children: <Widget>[
Container(
padding: const EdgeInsets.all(15),
child: Text(
'COVER LETTER:',
style: TextStyle(
color: Colors.teal,
fontSize: 25,
fontWeight: FontWeight.w500),
)),
Container(
child: Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
print(isSwitched);
});
},
activeTrackColor: Colors.teal,
activeColor: Colors.white,
)),
]),
Column(children: <Widget>[
isSwitched
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(10),
child: Text(
'NAME:',
style: TextStyle(
color: Colors.teal,
fontSize: 20,
fontWeight: FontWeight.w500),
)),
Container(
child: TextField(
decoration: new InputDecoration(
contentPadding:
const EdgeInsets.all(20.0),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal, width: 2.0),
),
hintText: 'Enter NAME'),
),
),
])
: Container(),
])
])),
);
}
}
The output for the above code is as follows:
Before button click
After Button click

how pass variable from a class to another class in flutter

I have the numOfItems set in this class and I want to use it in another class AddToCart, but I cant pass the variable successfully.. here is a sample code, please how can I do this, I cannot seem to figure it out, What I want to know is the best way to pass data after I have setState to the other class..
static int numOfItems = 1;
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
buildOutlineButton(
icon: Icons.remove,
press: () {
if(numOfItems > 1){
setState(() {
numOfItems--;
});
}
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: kDefaultPaddin / 2),
child: Text(
//"01",
numOfItems.toString().padLeft(2, "0"),
style: Theme.of(context).textTheme.headline,
),
),
buildOutlineButton(
icon: Icons.add,
press: () {
setState(() {
numOfItems++;
});
}),
],
);
}
SizedBox buildOutlineButton({IconData icon, Function press}) {
return SizedBox(
width: 32,
height: 32,
child: OutlineButton(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
onPressed: press,
child: Icon(icon),
),
);
}
}```
here is the second class where I want to use the numOfItems in the second class, how can I access the variable in this class.
```class AddToCart extends StatelessWidget {
const AddToCart({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Padding(
padding: const EdgeInsets.symmetric(vertical: kDefaultPaddin),
child: Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(right:kDefaultPaddin),
height:50,
width: size.width * 0.3,
decoration: BoxDecoration(
border: Border.all(color:primaryColorDark),
borderRadius: BorderRadius.circular(18),
),
child: IconButton(
icon: SvgPicture.asset(
"assets/icons/add_to_cart.svg", color: primaryColorDark,), //svgPicture.asser
onPressed: () {
// on press of the cart button
},
),
),
Expanded(
child: SizedBox(
height:50,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18)
),
color: primaryColor,
onPressed: (){
addProductToCart(context);
},
child: Text(
"Buy Now".toUpperCase(),
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
color: Colors.white,
)
),
),
),
)
],
),
);
}
void addProductToCart(BuildContext context) {
String quantityToSend = numOfItems
}
}
}```
What I want to know is the best way to pass data after I have setState to the other class..
You can use constructor to pass variable
Example:
Screen1:
class _TabsPageState extends State<TabsPage> {
int args = 3;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FlatButton(
color: Colors.blueAccent,
child: Text('Navigate to home', style: TextStyle(color: Colors.white),),
onPressed: () {
print('123');
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Tab2Page(args)));
},
),
),
);
}
}
Screen2:
class Tab2Page extends StatelessWidget {
final int args;
Tab2Page(this.args);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(args.toString()),
),
);
}
}
If you need only this variable " If it widget " just use the name of class x and then . then the name of static variable
i.e x.numOfItems
If this a another screen and you want to pass the data to this screen you can do it like this
class SecondScreen{
var anyVariable;
XScreen(this.anyVariable);
.......
......
}
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(anyVariable :numOfItems),
),
);
},

Executing Navigator.pop() when key pad is visible results in render flex error

I have noticed creating forms with flutter. That if there is Scaffold with a text field focused i.e the key pad visible if one presses the back button.
Navigator.pop();
This results in an render flex error.
I have tried wrapping the child in the single child scroll view components also tried setting the resize to avoid bottom padding property to true.
I still get the error.
Has anyone else experienced this ?
if so what is the solution and cause of the error ?
EDIT:
import 'package:flutter/material.dart';
class SettingsScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text(
"Settings",
style: TextStyle(
color: primaryColor,
fontFamily: titleFontStyle
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: primaryColor),
onPressed: () {
Navigator.of(context).pop();
},
),
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0.0,
),
backgroundColor: Colors.white,
body: Container(
// width: MediaQuery.of(context).size.width - 10.0,
// height: MediaQuery.of(context).size.height,
// padding: EdgeInsets.fromLTRB(20.0, 60.0, 20.0, 0.0),
child: SettingsForm(),
),
);
}
}
class SettingsForm extends StatefulWidget {
#override
_SettingsFormState createState() => _SettingsFormState();
}
class _SettingsFormState extends State<SettingsForm> {
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.only(top: 50.0),
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
),
SizedBox(height: 8.0),
RaisedButton(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 40.0),
textColor: Colors.white,
color: primaryColor,
child: Text(
'Update',
style: TextStyle(
color: Colors.white
),
),
onPressed: () {},
),
],
),
),
);
}
}
I have tried that, and it works fine. The keyboard layout will close when you press back button and navigate you to previous page.
Here is my 2 dart files below:
main.dart (From which I navigating through)
import 'settings.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new HomeScreen()
);
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: new Center(child: new Text("Click Mee")),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new SettingsForm()),
);
},
),
);
}
}
settings.dart (your provided code on next screen)
class SettingsForm extends StatefulWidget {
SettingsForm();
#override
_SettingsFormState createState() => _SettingsFormState();
}
class _SettingsFormState extends State<SettingsForm> {
final _formKey = GlobalKey<FormState>();
Color primaryColor = const Color.fromRGBO(3, 155, 226, 1);
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text(
"Settings",
style: TextStyle(
color: primaryColor
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: primaryColor),
onPressed: () {
FocusScope.of(context).unfocus();
Navigator.of(context).pop();
print("yes");
},
),
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0.0,
),
backgroundColor: Colors.white,
body: Container(
// width: MediaQuery.of(context).size.width - 10.0,
// height: MediaQuery.of(context).size.height,
// padding: EdgeInsets.fromLTRB(20.0, 60.0, 20.0, 0.0),
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.only(top: 50.0),
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
TextField(
autofocus: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username',
),
),
SizedBox(height: 8.0),
RaisedButton(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 40.0),
textColor: Colors.white,
color: primaryColor,
child: Text(
'Update',
style: TextStyle(
color: Colors.white
),
),
onPressed: () {},
),
],
),
),
),
),
);
}
}
The issue was that when I navigate back to the previous component. It was the previous component that overflowed.
I had used Column in the said component.
Converting it into ListView solved the error.