Click button in child widget not detected in parent function - flutter

I am trying to understand how state works with Flutter, I have a child widget that needs to change something in the Parent widget. I can detect the push on the button in the child using a print. However when i try to bubble up this change to the parent its not catching it.
I have been though a number of tutorials and im not 100% sure I understand how state works or should work, I think I am missing something here.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
//Consider this function as your _onNotification and important to note I am using setState() within :)
void _incrementCounter() {
print("pressed"); // Does not detect pressed.
setState(() {
_counter++; // counter is not increased
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: Colors.white),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button $_counter times:',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
],
),
),
floatingActionButton: MyFloatButton(
_incrementCounter), //Pass delegate to _incrementCounter method
);
}
}
class MyFloatButton extends StatefulWidget {
// Here I am receiving the function in constructor as params
const MyFloatButton(this.onPressedFunction, {super.key});
// Should be the delegated function from _MyHomePageState
final Function onPressedFunction;
#override
_MyFloatButtonState createState() => new _MyFloatButtonState();
}
class _MyFloatButtonState extends State<MyFloatButton> {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: new BorderRadius.circular(50.0)),
child: IconButton(
icon: Icon(Icons.add),
color: Colors.white,
onPressed: () => {
//print('pressed') // Does work shows button pressed
widget.onPressedFunction
}, // call the delegated method to detect the pressed
),
);
}
}
Things tried:
onPressed: widget.onPressedFunction()
Results in
setState() or markNeedsBuild called during build
onPressed: widget.onPressedFunction
Results in
The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.
onPressed: () => widget.onPressedFunction,
Results in
No change does not do anything

Please try this. onPressedFunction is a function so declare like below function.
onPressed: () => {
widget.onPressedFunction()
},

Inside the MyFloatButton you're calling a function inside a function
onPressed: () => {
//print('pressed') // Does work shows button pressed
widget.onPressedFunction
},
It should be as follows
onPressed: widget.onPressedFunction

Change this
onPressed: () => {
//print('pressed') // Does work shows button pressed
widget.onPressedFunction
},
To this
onPressed: () => widget.onPressedFunction,
Just remove curly braces and add () here
floatingActionButton: MyFloatButton(
_incrementCounter())

Related

How to change the value and the function of a button on flutter?

I have a function named saveData which is executed on pressing a button. I want if I click on the button I execute saveData function and the value of the button become stop then when I click on stop the function should be fininish.
this is the button code:
Align(
alignment: Alignment.bottomCenter,
child: TextButton(
onPressed: () {
saveData();
},
child: Text('Save Data'),
),
),
One way to achieve what you want is simply to create a flag to control which button (text/action) is shown at any given moment:
TextButton(
onPressed: isSaving ? Finish : saveData,
child: isSaving ? const Text("Stop") : const Text("Save Data"),
)
Try the following working complete sample to see what i mean:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isSaving = false;
Future saveData() async {
isSaving = true;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Saving data..."),duration: Duration(hours: 1),)
);
setState(() { });
}
void Finish() {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Saving data stopped..."),duration: Duration(seconds: 1),)
);
isSaving = false;
setState(() { });
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: TextButton(
onPressed: isSaving ? Finish : saveData,
child: isSaving ? const Text("Stop") : const Text("Save Data"),
)
),
);
}
}
This will produce a result like:
State 1
After Save Data is tapped
You need state management.
State Management
This is a way to manage your user interface controls such as text fields, buttons, images, etc. It controls what and when something should display or perform an action. More about Flutter state management here
Codebase Sample
String name = ""; // setting an empty name variable
Align(
alignment: Alignment.bottomCenter,
child: TextButton(
onPressed: () {
setState(() {
name = "new name"; // updating the name variable with setState
});
},
child: Text('Save Data'),
),
),
Now, to implement your idea. You need a bool variable that changes the state on the button click action. To do that, look what I did below
bool isClicked = false;
Align(
alignment: Alignment.bottomCenter,
child: TextButton(
onPressed: () {
setState(() => isClicked = !isClicked); // change click state
if (isClicked) {
// do something on click
} else {
// do something off click
}
},
child: Text(isClicked ? "Stop" : "Save Data"), // if isClicked display "Stop" else display "Save Data"
),
),
Another way to do this is to create two different functions. One for saving user data, and the other of stop and calling the action based on a bool state.
onPressed: isSaving ? saveData : stop,
You can use the method above to update your user data as well if any misunderstand or need future help, comment below. Bye
Basically this is a state management problem.
you get more information about state management from here
Here a code for solve your problem
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(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeView(),
);
}
}
class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);
#override
State<HomeView> createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
bool _savePressed = false;
void _save() {
// TODO do whatever you want
}
void _stop() {
// TODO do whatever you want
}
void _onButtonPressed() {
setState(() {
_savePressed = !_savePressed;
_savePressed ? _save() : _stop();
});
}
String get _getButtonText => _savePressed ? "Stop" : "Save";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Align(
alignment: Alignment.bottomCenter,
child: TextButton(
onPressed: _onButtonPressed,
child: Text(_getButtonText),
),
),
);
}
}

'setState' not working in navigated page if custom color is used

For some reason, whenever I navigate to another route using the way described in flutter's documentation i.e https://flutter.dev/docs/cookbook/navigation/navigation-basics, and if I have used custom color in the following way:
color: Color(0xff0e0f26),
in that route, the setState method doesn't work in it. However, if I use color in the following way: color: Colors.blue, the setState method works. I have no idea what is causing this. I want to use a color value that is not present amongst the colors that flutter provides. How do I fix this? The full code along with explanation (using comments) is here:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: homepage(),
);
}
}
class homepage extends StatefulWidget{
#override
_homepageState createState() => _homepageState();
}
class _homepageState extends State<homepage>{
#override
Widget build(BuildContext context){
return Scaffold(
body: Container(
alignment: Alignment.center,
color: Color(0xff0e0f26),
child: RaisedButton(
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
)
);
}
}
class SecondRoute extends StatefulWidget{
#override
_SecondRouteState createState() => _SecondRouteState();
}
class _SecondRouteState extends State<SecondRoute>{
bool test = false;
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text("Second"),
),
body: Container(
alignment: Alignment.center,
color: Color(0xff0e0f26), //Here, if I use 'color: Colors.blue', setState works.
child:Column(
children: [
RaisedButton(
onPressed: (){ //When the button is pressed, setState is triggered.
setState((){ //This should theoretically rebuild the widget with 'test' becoming true
//, thus showing the text widget below in the screen, but it doesn't.
test = true;
});
},
),
test ? Text("HELLO"):SizedBox(), //I want 'test' to become true, thus making the text
//widget come on screen.
],
),
),
);
}
}
Thank you.
Your text ist just too dark.
If you use
test ? Text("HELLO", style: TextStyle(color: Colors.white30),):SizedBox(),
it should work. This just makes your text lighter. You should use ElevatedButton instead of RaisedButton, since RaisedButton is deprecated and could cause problems as well.

Show tooltip once page initialized - Flutter

I need to show a hint/tooltip for the userto indicate the user can get his current location by pressing the button. Have included the Tooltip in the code but only when the user does a long press of the button the tooltip is appearing, i want the tooltip to appear when the screen is initialized.
Code:
GlobalKey _toolTipKey = GlobalKey();
GestureDetector(
onTap: () {
final dynamic tooltip = _toolTipKey.currentState;
tooltip.ensureTooltipVisible();
},
child: Tooltip(
key: _toolTipKey,
message: 'Get current Location',
child: CircleAvatar(
radius: 30,
child: IconButton(
onPressed: getLocation,
icon: Icon(
Icons.my_location,
color: Colors.white,
),
),
),
),
)
I recently had to implement the same thing and I after lot of trying I managed to get it working.
You can use stateful widget and call the function to show tooltip in its initState. Now I got the same error as another person.
The method ensureTooltipVisible was called on null.
To solve this, I had to call
await Future.delayed(Duration(milliseconds: 10));
before ensureTooltipVisible() function.
#override
void initState() {
super.initState();
showTooltipIfOnboadingComplete();
}
and the function to show and close tooltip after certain amount of time,
Future showAndCloseTooltip() async {
await Future.delayed(Duration(milliseconds: 10));
tooltipkey.currentState.ensureTooltipVisible();
await Future.delayed(Duration(seconds: 4));
tooltipkey.currentState.deactivate();
}
you will also have to set you Tooltip widget trigger mode as TooltipTriggerMode.manual,
Here is complete code;
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const FloatingSupportButton()
);
}
}
class FloatingSupportButton extends StatefulWidget {
const FloatingSupportButton({Key? key}) : super(key: key);
#override
State<FloatingSupportButton> createState() => _FloatingSupportButtonState();
}
class _FloatingSupportButtonState extends State<FloatingSupportButton> {
// final GlobalKey<TooltipState> tooltipkey = GlobalKey<TooltipState>();
final tooltipkey = GlobalKey<State<Tooltip>>();
#override
void initState() {
super.initState();
showAndCloseTooltip();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.center,
child: Tooltip(
message: "Hello",
triggerMode: TooltipTriggerMode.manual,
key: tooltipkey,
preferBelow: false,
child: FloatingActionButton(
child: const Icon(Icons.add),
shape: const CircleBorder(
side: BorderSide(
color: Colors.white,
),
),
backgroundColor: const Color(0xFFc60c0c),
onPressed: () {
showAndCloseTooltip();
},
),
),
),
);
}
Future showAndCloseTooltip() async {
await Future.delayed(const Duration(milliseconds: 10));
// tooltipkey.currentState.ensureTooltipVisible();
final dynamic tooltip = tooltipkey.currentState;
tooltip?.ensureTooltipVisible();
await Future.delayed(const Duration(seconds: 4));
// tooltipkey.currentState.deactivate();
tooltip?.deactivate();
}
}
Have a great day everyone, hope this was helpful !!
You should use Statefulwidget and in initState write below code
import 'package:flutter/scheduler.dart';
#override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) {
// Flutter get callback here when screen initialized.
final dynamic tooltip = _toolTipKey.currentState;
tooltip.ensureTooltipVisible();
});
}
Here the Full Source code When you run the app it directly shows "Get current Location" tooltip
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key? key, required this.title}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
GlobalKey _toolTipKey = GlobalKey();
#override
void initState() {
super.initState();
SchedulerBinding.instance!.addPostFrameCallback((_) {
// Flutter get callback here when screen initialized.
final dynamic tooltip = _toolTipKey.currentState;
tooltip.ensureTooltipVisible();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Tooltip(
key: _toolTipKey,
message: 'Get current Location',
child: CircleAvatar(
radius: 30,
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.my_location,
color: Colors.white,
),
),
),
),
],
),
),
);
}
}

Flutter/Dart: A TextEditingController was used after being disposed

Please, someone, help on this, I am not sure if this is a framework glitch then how are there not more post on this and if it is me then how come there is not much on this error!
===========================
main.dart
import 'package:flutter/material.dart';
import 'dialog_reusable.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog( context: context, builder: (context) { return MyDialog(); });
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
===========================
dialog_reusable.dart
import 'package:flutter/material.dart';
import 'dialog_reusable.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog( context: context, builder: (context) { return MyDialog(); });
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
===========================
===========================
Steps to Reproduce
The Textfield is part of a Dialog() along with 2 buttons 'ok' and 'cancel'
Create a new Flutter project with standard options
Remove the files in LIB folder
Make new files with the code and name provided above
When the Dialog() pops up and the 'cancel' button is clicked the following error happens.
════════ Exception caught by widgets library ════════
The following assertion was thrown building MouseRegion(listeners: [enter, exit], state: _MouseRegionState#1877d):
A TextEditingController was used after being disposed.
Once you have called dispose() on a TextEditingController, it can no longer be used.
The relevant error-causing widget was:
TextField file:///C:/MobileApps/Apps/Clima-Flutter/lib/utilities/mydialog.dart:90:15
When the exception was thrown, this was the stack:
#0 ChangeNotifier._debugAssertNotDisposed. (package:flutter/src/foundation/change_notifier.dart:106:9)
#1 ChangeNotifier._debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:112:6)
#2 ChangeNotifier.removeListener (package:flutter/src/foundation/change_notifier.dart:167:12)
#3 _AnimatedState.didUpdateWidget (package:flutter/src/widgets/transitions.dart:159:28)
#4 StatefulElement.update (package:flutter/src/widgets/framework.dart:4690:58)
Steps Tried:
Disable the Textfield before Dispose() by using a variable in 'enable' property of Textfield
Assign NULL to 'Controller' property of TextField if the variable that holds enable property for TextField is false before Dispose(), via the ternary operator and if clause
Assign NULL to 'onChanged:' property of TextField if the variable that holds enable property for TextField is false before Dispose(), via the ternary operator and if clause
To prevent getting the error Flutter/Dart: A TextEditingController was used after being disposed, the previously disposed TextEditingController shouldn't be used again. One way that you can do here is pass a new instance of TextEditingController to be used in the AlertDialog, or depending on how you use a TextEditingController.
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var textEditingController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(
'You have entered ${textEditingController.text}',
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => alertDialog(textEditingController),
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
alertDialog(TextEditingController textEditingController) {
return showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: TextField(
controller: textEditingController,
decoration: const InputDecoration(hintText: 'Enter Something'),
),
actions: <Widget>[
TextButton(
child: const Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text(
"OK",
style: TextStyle(color: Colors.red),
),
onPressed: () {
setState(() {
// Triggers a Widget rebuild to update textEditingController state
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
}

How do I access BuildContext outside of a stateful or stateless widget?

I created a class that extends the AppBar class in Flutter so I can reuse it whenever I need it.
My problem is how do I access the Stateful/Stateless widget build context?
class AppBarLayout extends AppBar {
static final AppController _appController = new AppController();
final GlobalKey<ScaffoldState> _scaffoldKey;
final String appBarTitle;
AppBarLayout(this.appBarTitle,this._scaffoldKey): super(
title: Text(appBarTitle),
leading: IconButton(
onPressed: () => _scaffoldKey.currentState.openDrawer(),
iconSize: 28,
icon: Icon(Icons.menu,color: Colors.white),
),
actions: <Widget>[
IconButton(
onPressed: () => _appController.signOut().then((_) {
_appController.navigateTo(context, new GoogleSignView());
}),
icon: Icon(Icons.account_box),
padding: EdgeInsets.all(0.0),
),
],
);
}
You would need to wrap your Scaffold in a Staless or Stateful widget, so you can get the context, e.g.
import 'package:flutter/material.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: 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> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarLayout(GlobalKey(debugLabel: 'someLabel'), appBarTitle: 'The Title', context: context,),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class AppBarLayout extends AppBar {
final GlobalKey<ScaffoldState> _scaffoldKey;
final String appBarTitle;
final BuildContext context;
AppBarLayout(this._scaffoldKey, {this.appBarTitle, this.context}): super(
title: Text(appBarTitle),
leading: IconButton(
onPressed: () => _scaffoldKey.currentState.openDrawer(),
iconSize: 28,
icon: Icon(Icons.menu,color: Colors.white),
),
actions: <Widget>[
IconButton(
onPressed: () {
print('Button pressed');
},
icon: Icon(Icons.account_box),
padding: EdgeInsets.all(0.0),
),
],
);
}
Here I'm using a very similar Widget of what you have.