Flutter: call parent function from child widget - flutter

hi there 👋🏼 i would like to call a function from a child widget (customappbar) for example to open the drawer.
there is my code:
home_page.dart
import 'package:fahrschuleapp/widget/appbar_widget.dart';
import 'package:fahrschuleapp/widget/sidebar_widget.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
drawerEnableOpenDragGesture: false,
body: SafeArea(
child: Center(
child: Column(
children: [
CustomAppBar(
pFunction: CustomAppBarFunction.menu,
pContext: context,
pTitle: 'test',
),
],
),
),
),
drawer: SideBar(),
);
}
}
i tried to say with the parameter "pFunction" which function should be called
for example navigator pop or open menu etc inside the _callFunction
appbar_widget.dart
import 'package:flutter/material.dart';
enum CustomAppBarFunction {
menu,
back,
exit,
}
class CustomAppBar extends StatelessWidget {
CustomAppBar({
Key? key,
required this.pTitle,
required this.pContext,
required this.pFunction,
}) : super(key: key);
CustomAppBarFunction pFunction;
String pTitle;
BuildContext pContext;
final List<IconData> _iconList = [
Icons.menu,
Icons.arrow_back,
Icons.close,
];
_callFunction(int index) {
switch (index) {
case 0:
Scaffold.of(pContext).openDrawer();
break;
default:
break;
}
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(
left: 20,
right: 20,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.all(8),
child: IconButton(
onPressed: _callFunction(pFunction.index),
icon: Icon(
_iconList[pFunction.index],
),
),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(15)),
color: Theme.of(context).colorScheme.primary,
),
),
Container(
padding: const EdgeInsets.only(left: 15, right: 15),
child: Text(
pTitle,
style: const TextStyle(
fontFamily: 'Hellix',
fontSize: 20,
),
),
),
const SizedBox(
width: 50.4,
),
],
),
);
}
}
i tried to call inside the widget the _callFunction but this doesnt work
error output:
Scaffold.of() called with a context that does not contain a Scaffold.
how can i solve it? or is there a better way to do that?

Change you IconButton as below code,
Builder(builder: (context) {
return IconButton(
onPressed:() => _callFunction(pFunction.index, context),
icon: Icon(
_iconList[pFunction.index],
),
) ;
})
And change your _callFunction,
_callFunction(int index, BuildContext mContext) {
switch (index) {
case 0:
Scaffold.of(mContext).openDrawer();
break;
default:
break;
}
}

Scaffold.of() called with a context that does not contain a Scaffold.
This message appears when you try to access a Scaffold from a context that does not have a Scaffold above it. You can use a Key for that purpose. Create a GlobalKey and assign it to the Scaffold, then pass the Key to the AppBar from where you can access the Scaffold.

Related

A RenderFlex overflowed by 141 pixels on the bottom

I added a bottom navigation bar on the bottom of the screen but it has interfered with the overflowed pixels. A part of my code which is the CartTotal() wasnt shown in the code. I tried using Listview but im not able to add both of the items in the column for both CartProducts() and CartTotal(). This was the suggestion:
Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.
import 'package:flutter/material.dart';
import '../../widgets/cart_products.dart';
import '../../widgets/cart_total.dart';
import 'package:grocery_shopping/widgets/widgets.dart';
import '../Home/components/bottom_bar.dart';
import '../Home/components/enum.dart';
class CartScreen extends StatelessWidget {
const CartScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Your Cart")),
bottomNavigationBar: const CustomBottomBar(selectMenu: MenuState.cart),
body: Column(
children: [
CartProducts(),
CartTotal(),
],
),
);
}
}
this is my CartProducts()
import 'package:flutter/material.dart';
import 'package:grocery_shopping/controllers/cart_controller.dart';
import 'package:grocery_shopping/models/product_model.dart';
import 'package:get/get.dart';
class CartProducts extends StatelessWidget {
final CartController controller = Get.find();
CartProducts({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Obx(
() => SizedBox(
height: 600,
child: ListView.builder(
itemCount: controller.products.length,
itemBuilder: (BuildContext context, int index) {
return CartProductCard(
controller: controller,
product: controller.products.keys.toList()[index],
quantity: controller.products.values.toList()[index],
index: index,
);
}),
),
);
}
}
class CartProductCard extends StatelessWidget {
final CartController controller;
final Product product;
final int quantity;
final int index;
const CartProductCard({
Key? key,
required this.controller,
required this.product,
required this.quantity,
required this.index,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
product.imageUrl,
),
),
SizedBox(
width: 20,
),
Expanded(
child: Text(product.name),
),
IconButton(
onPressed: () {
controller.removeProduct(product);
},
icon: Icon(Icons.remove_circle),
),
Text('$quantity'),
IconButton(
onPressed: () {
controller.addProduct(product);
},
icon: Icon(Icons.add_circle),
),
],
),
);
}
}
This is my CartTotal()
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:grocery_shopping/controllers/cart_controller.dart';
import 'package:get/get.dart';
class CartTotal extends StatelessWidget {
final CartController controller = Get.find();
CartTotal({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Obx(
() => Container(
padding: const EdgeInsets.symmetric(horizontal: 75),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Text(
'\RM${controller.total}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
],
)),
);
}
}

The context you are using comes from the widget above the BlocProvider. I use Dialog

Faced a problem when adding Bloc. I use Counter which is in Dialog and do everything through Block but for some reason I got this error (see below). I did the same before and there was no error. I do not fully understand what the error is connected with and how to solve it correctly. I have a HomePage class in which I declare Bloc and in which the HomeBody class is nested, and in this class there is a button for opening Dialog (FilterDialog) and in this Dialog I have a Counter that I did through Bloc. I will be grateful for help.
home page
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocProvider<CounterCubit>(
create: (context) => CounterCubit(),
child: Scaffold(
extendBodyBehindAppBar: true,
appBar: LogoAppBar(
buttonIcon: SvgPicture.asset(constants.Assets.burgerMenu)),
body: const HomeBody(),
),
);
}
}
home body
class HomeBody extends StatelessWidget {
const HomeBody({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Container(
width: size.width,
height: size.height,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/background/main_background.png'),
fit: BoxFit.cover,
),
),
child: _child(context, size),
);
}
Widget _child(context, Size size) => Padding(
padding: const EdgeInsets.only(top: 121, right: 24),
child: Align(
alignment: Alignment.topRight,
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return const FilterDialog();
},
);
},
child: Container(
height: 40,
width: 50,
decoration: const BoxDecoration(
color: Colors.amber,
),
alignment: Alignment.center,
child: const Text('Dialog'),
),
),
),
);
}
FilterDialog
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Dialog(
insetPadding: const EdgeInsets.only(top: 100, left: 24, right: 24),
backgroundColor: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(24))),
child: Container(
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
color: constants.Colors.greyDark,
borderRadius: BorderRadius.all(Radius.circular(24)),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(21, 38, 21, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PriceCounter(title: 'From'),
]
price counter
class PriceCounter extends StatelessWidget {
final String title;
const PriceCounter({Key? key, required this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
final CounterCubit cubit = BlocProvider.of<CounterCubit>(context);
return Column(
children: [
BlocBuilder<CounterCubit, CounterState>(
builder: (context, state) => InputField(
price: state.countValue.toString(),
textStyle: constants.Styles.normalBookTextStyleWhite),
),
Row(
children: [
IconButton(
onPressed: () => cubit.increment(),
icon: SvgPicture.asset(constants.Assets.plus),
constraints: const BoxConstraints(),
padding: EdgeInsets.zero,
),
Text('Test', style: constants.Styles.smallLtStdTextStyleWhite),
IconButton(
onPressed: () => cubit.decrement(),
icon: SvgPicture.asset(constants.Assets.minus),
constraints: const BoxConstraints(),
padding: EdgeInsets.zero,
),
],
)
],
);
}
}
counter state
class CounterState {
final double countValue;
const CounterState({required this.countValue});
}
counter cubit
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(const CounterState(countValue: 0.13));
void increment() => emit(CounterState(countValue: state.countValue + 0.1));
void decrement() => emit(CounterState(countValue: state.countValue - 0.1));
}
The following assertion was thrown building PriceCounter(dirty):
BlocProvider.of() called with a context that does not contain a CounterCubit.
No ancestor could be found starting from the context that was passed to BlocProvider.of<CounterCubit>().
This can happen if the context you used comes from a widget above the BlocProvider.
The context used was: PriceCounter(dirty)
The relevant error-causing widget was PriceCounter
lib\…\widgets\filter_dialog.dart:233 When the exception was thrown,
this was the stack
Unfortunately, your FilterDialog cannot find the CounterCubit provider, since showDialog is a bit tricky about it, so you have to re-supply your CounterCubit to FilterDialog in this way:
Widget _child(context, Size size) => Padding(
padding: const EdgeInsets.only(top: 121, right: 24),
child: Align(
alignment: Alignment.topRight,
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return BlocProvider.value( // in this way
value: CounterCubit(),
child: FilterDialog(),
);
},
);
},
child: Container(
height: 40,
width: 50,
decoration: const BoxDecoration(
color: Colors.amber,
),
alignment: Alignment.center,
child: const Text('Dialog'),
),
),
),
);
}
With BlocProvider.value you do not create a Bloc, but only assign to its child the bloc that you have already created in HomePage.
That should work, but if for some reason you are going to use this CounterCubit in another page and you don't want to use BlocProvider.value again, I strongly suggest that you make it global, in other words that you provide the CounterCubit in all your application in this way :
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => CounterCubit(), // here
child: MaterialApp(
title: 'Material App',
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
}
With this, now every application will be able to get the context of your CounterCubit.
With both codes, one with the BlocProvider.value or without it and using it global, it works.

Flutter - Row added -> change the text of a container

I'm quite inexperienced with flutter and have created this script.
When you tap on the red container you create a Row of buttons,
I would like when I click on a button in the Row -> the text of the blue container becomes the same as the text contained in the tapped button
Anyone know how I can do?
Thank you :)
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Chat(),
);
}
}
class Chat extends StatefulWidget {
const Chat({Key? key}) : super(key: key);
#override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
String text = 'Henlo i am Gabriele!';
List<Container> OutputList = [];
void tool(String text) async {
List ListText = text.split(' ');
for (var i in ListText) {
OutputList.add(
Container(
child: GestureDetector(
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(i),
),
),
),
),
),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
tool(text);
print(OutputList);
});
},
child: Container(
width: 150.0,
height: 50.0,
color: Colors.red,
child: Center(child: Text('START ->')),
),
),
SizedBox(height: 50.0),
Row(
children: OutputList,
),
SizedBox(height: 50.0),
Container(
color: Colors.blue,
width: 200.0,
height: 50.0,
child: Text(''),
),
],
),
),
);
}
}
Yes you can add a few line of code check here i try to solve.
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: Chat(),
);
}
}
class Chat extends StatefulWidget {
const Chat({Key? key}) : super(key: key);
#override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
String text = 'Henlo i am Gabriele!';
//step 1 create variable
String newGeneratedText = "";
List<Container> OutputList = [];
void tool(String text) async {
List ListText = text.split(' ');
for (var i in ListText) {
OutputList.add(
Container(
child: GestureDetector(
onTap: () {
//add logic here to concatinate values
setState(() {
newGeneratedText = newGeneratedText + " " + i;//added " " for one space
});
},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(i),
),
),
),
),
),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
tool(text);
print(OutputList);
});
},
child: Container(
width: 150.0,
height: 50.0,
color: Colors.red,
child: Center(child: Text('START ->')),
),
),
SizedBox(height: 50.0),
Wrap( // added for fixing more values and solve overflow exceptions error
children: OutputList,
),
SizedBox(height: 50.0),
Container(
color: Colors.blue,
width: 200.0,
height: 50.0,
child: Text(newGeneratedText), //final print values
),
],
),
),
);
}
}

error [Get] the improper use of a GetX has been detected. using bottomNavigationBar

I'm trying to implement a bottomNavigationBar, but I can't finish it, I'm using Get to handle the routes and the state of the application.
I'm new to flutter, but reading the documentation I still don't understand
This is the main widget.
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: AppColors.black,
title: Center(
child: CommonAssetImage(
asset: 'logo.png',
color: AppColors.white,
height: 30,
),
),
),
body: BodyTabsScreen(),
bottomNavigationBar: HomeScreenBottomNavigatorBar()),
);
}
then,I have this widget where call other widget.In this widget I using Obs.
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Obx(() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
}),
),
);
}
}
class TabsScreenBottomNavigationTab extends StatelessWidget {
final String label;
final IconData icon;
final Widget image;
final VoidCallback onTap;
final bool isActive;
final double iconSize;
const TabsScreenBottomNavigationTab({
Key key,
this.label,
this.icon,
this.image,
this.onTap,
this.isActive,
this.iconSize = 20,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final _inactiveTextStyle = Theme.of(context).textTheme.bodyText2;
final _activeTextStyle =
_inactiveTextStyle.copyWith(color: AppColors.white);
const _commonDuration = Duration(milliseconds: 200);
final _availableSpace = MediaQuery.of(context).size.width - 27 * 2;
final _inactiveWidth = _availableSpace * .2;
final _activeWidth = _availableSpace * .35;
return AnimatedContainer(
duration: _commonDuration,
width: isActive ? _activeWidth : _inactiveWidth,
height: 35,
child: Material(
color: Colors.transparent,
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: AnimatedContainer(
duration: _commonDuration,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: AnimatedDefaultTextStyle(
style: isActive ? _activeTextStyle : _inactiveTextStyle,
duration: _commonDuration,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null)
Icon(
icon,
size: iconSize,
color: isActive ? AppColors.white : AppColors.black,
),
if (image != null) image,
if (isActive)
Container(
margin: const EdgeInsets.only(left: 8),
child: Text(label),
)
],
),
),
),
),
),
),
);
}
}
Getx will always throw that error when you use Obx or Getx widget without inserting an observable variable that widget. So if you are NOT trying to rebuild a widget based on an updated value of a variable that lives inside a class that exends GetxController, then don't use a Getx widget.
If you're just trying to use Getx for routing, then make sure to change your MaterialApp to GetMaterialApp and define your routes, like so.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GetMaterialApp(
home: Page1(),
getPages: [
GetPage(name: Page1.id, page: () => Page1()), // add: static const id = 'your_page_name'; on each page to avoid using raw strings for routing
GetPage(name: Page2.id, page: () => Page2()),
],
);
}
}
Then in the onTap of your bottom navigation bar just use
Get.to(Page2());
Just remove the Obx widget wrapping your Row widget like this:
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
),
);
}
}
Why? Because you are not using any observable (obs/Rx) variable in your widget tree which would trigger a rebuild when the value changes. So GetX is complaining and for good reason.
The controller should be inside Obx other wise its shows this error.
LeaderBoardController controller = Get.put(getIt<LeaderBoardController>());
Obx(()=>controller.leadBoardModel != null
? Column(
children: [
Container(
height: 180,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LeadBoardImage(type: LEADTYPE.NORMAL),
LeadBoardImage(type: LEADTYPE.CROWN),
LeadBoardImage(type: LEADTYPE.NORMAL)
]),
),
Expanded(
flex: 4,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 10.w),
children: [
for (int i = 4; i < controller.leadBoardModel!.data.result.length; i++)
LeaderBoardListItem(result:controller.leadBoardModel!.data.result[i])
],
),
)
],
)
: LoadingContainer()),
It happens when you don't use your controller value in your widget. That's why it gives error because there is no sense in using Obx or Getx() widget
MainController controller = Get.find();
return Obx(
()
{
return Column(
children: [
Text("My pretty text")
],
);
}
);
Solution :
MainController controller = Get.find();
Obx(
()
{
return Column(
children: [
Text(controller.text)
],
);
}
);
Please note that there are two required aspects: 1) extending from a GetXController, and 2) The field/method returning a value from the controller, must be computed from a Rx type. In my case, I made a sub-class of a GetXController for a test, and the return value was hard-coded (not based on a Rx value), and the ObX error occurred.
For Current Scenario You dont need to use getx for this page
(Its not proper Implementation) . please remove the OBX() your error will gone .
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
}),
),
}

Flutter dynamic text in RawMaterialButton

I am creating my own style button in flutter. So far I created a commonui.dart file and placed the following code
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
CustomButton({#required this.onPressed});
final GestureTapCallback onPressed;
#override
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
SizedBox(
width: 10.0,
),
Text(
"Tap Me",
maxLines: 1,
style: TextStyle(color: Colors.white,fontFamily: 'ActoBold'),
),
],
),
),
onPressed: onPressed,
);
}
}
And calling it from my pages like this
CustomButton(
onPressed: () {
print("Tapped Me");
},
)
I would likes to make the button text dynamic. How to pass the variable to the CustomButton widget ?
Do it like you just did for the onPressed function. Only difference is that the type will be String.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
final GestureTapCallback onPressed;
final String buttonText;
CustomButton({#required this.onPressed, this.buttonText});
#override
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
SizedBox(
width: 10.0,
),
Text(
buttonText ?? 'Tap me',
maxLines: 1,
style: TextStyle(color: Colors.white,fontFamily: 'ActoBold'),
),
],
),
),
onPressed: onPressed,
);
}
}
Then you can pass your value to CustomButton.
CustomButton(
buttonText: 'Updated Text',
onPressed: () {
print("Tapped Me");
},
)
If you want to change the value dynamically when you click the button, use a stateful widget:
class App extends StatefulWidget {
#override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
String _buttonText;
Widget build(BuildContext context) {
return Scaffold(
body: CustomButton(
buttonText: _buttonText,
onPressed: () {
print("Tap Me");
setState(() {
_buttonText = 'Tapped';
});
},
),
);
}
}
Do following changes...
CustomButton(
child: Text(trigger),
onPressed: () {
setState((){
trigger="tapped me";
})
},
)
dont forget to declare variable and change your class stateless to stateful widget.