In flutter How to call method in Container on click of button? - flutter

In My flutter app, I have designed three buttons, now I want to call three methods on click of the buttons.
This is my screen:enter image description here
If i click on View button I want to call ViewAll() method. If I click on Rejected button then I want to call Reject() method. If I click on Accepted button then I want to call Accept() method.
This is my code:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("Reallocation", style: TextStyle(color: Colors.white)),
iconTheme: IconThemeData(color: Colors.white),
),
backgroundColor: Colors.white,
body: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: SizedBox(height: 5),
),
SliverToBoxAdapter(
child: Center(
child: _tags1(context),
heightFactor: 1.5,
),
),
SliverToBoxAdapter(child: Divider(color: Colors.grey)),
SliverToBoxAdapter(
child: Center(
//child: ViewAll(context,resultCheck3),
)
)
]
),
);
}
This widget for design buttons:
Widget _tags1 (BuildContext context){
return Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Padding(padding: EdgeInsets.only(left:15.0)),
Container(
child:RaisedButton(
shape: Border.all(width: 2.0, color: Colors.lightBlue),
child: Text("View"),
onPressed: (){
})
),
Padding( padding: EdgeInsets.only(left:25.0)),
Container(
child:RaisedButton(
shape: Border.all(width: 2.0, color: Colors.lightBlue),
child: Text("Rejected"),
onPressed: (){
// some code here
})
),
Padding( padding: EdgeInsets.all(8)),
Container(
child:RaisedButton(
shape: Border.all(width: 2.0, color: Colors.lightBlue),
child: Text("Accepted"),
onPressed: (){
// some code here
})
)
],
)
],
),
);
}
Now i have called ViewAll() method directly in Body without on click.
I have 3 different buttons and 3 different methods.

You can directly call the method in onPressed method of the RaisedButton.
Container(
child:RaisedButton(
shape: Border.all(width: 2.0, color: Colors.lightBlue),
child: Text("Rejected"),
onPressed: Rejected // this will the method for your rejected Button
)
This is just an example, You will have to figure out by yourself for the desired output you want. It's little difficult to give the exact solution.
Example:
int _viewFlag = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("Reallocation", style: TextStyle(color: Colors.white)),
iconTheme: IconThemeData(color: Colors.white),
),
backgroundColor: Colors.white,
body: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: SizedBox(height: 5),
),
SliverToBoxAdapter(
child: Center(
child: _tags1(context),
heightFactor: 1.5,
),
),
SliverToBoxAdapter(child: Divider(color: Colors.grey)),
SliverToBoxAdapter(
child: _viewFlag == 1 ? Center(
child: ViewAll(context,resultCheck3),
) : _viewFlag == 2 ? Center(
child: RejectAll(context,resultCheck3),
) : Center(
child: AcceptAll(context,resultCheck3),
)
)
]
),
);
}

You can simply call your method in => "on pressed(){}".
Example:
{ _yourMethod(){
// some code in here...
}
//...
FlatButton(
onPressed: _yourMethod,
child: const Text('Sign In',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold
),
),
color: Colors.red,
),

Related

Flutter how to add a dialog screen over main screen like this

Hi all,
I would like to add a screen that slowly appears form the bottom or the screen and partially covers the main screen below. So you can still see the top part of the main screen. Does anyone know how to do this?
Thank you very much
for this you can use showModalBottomSheet method the simple example is
import 'package:flutter/material.dart';
void main() => runApp(const BottomSheetApp());
class BottomSheetApp extends StatelessWidget {
const BottomSheetApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Bottom Sheet Sample')),
body: const BottomSheetExample(),
),
);
}
}
class BottomSheetExample extends StatelessWidget {
const BottomSheetExample({super.key});
#override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: const Text('showModalBottomSheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
color: Colors.amber,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Modal BottomSheet'),
ElevatedButton(
child: const Text('Close BottomSheet'),
onPressed: () => Navigator.pop(context),
),
],
),
),
);
},
);
},
),
);
}
}
you can read more about this method here
You can use showModalBottomSheet() same as below...
showModalBottomSheet<void>(
// context and builder are
// required properties in this widget
context: context,
builder: (BuildContext context) {
// we set up a container inside which
// we create center column and display text
// Returning SizedBox instead of a Container
return SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text('HERE You'll add all your content'),
],
),
),
);
},
);
You can call above method in
initState() of screen or buttons onPressed or onTap.
As per your shared Image I have try something like that Using ModalBottomSheet
Your Button Widget
ElevatedButton(
child: const Text('Show Modal BottomSheet'),
onPressed: () {
showModalBottomSheet<void>(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
),
context: context,
builder: (BuildContext context) {
return modelSheet(context);
},
);
},
)
bottomSheet Widget:
modelSheet(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: const BoxDecoration(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.hourglass_empty_outlined,
color: Colors.red,
size: 40,
),
const SizedBox(
height: 10,
),
const Text(
'Beta version',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.check,
color: Colors.red,
),
Text('better price')
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.check,
color: Colors.red,
),
Text('early access')
],
),
const SizedBox(
height: 20,
),
RichText(
text: const TextSpan(
text:
'Please mind that this is a beta version of the app. As a founding member you can get',
style: TextStyle(fontSize: 20, color: Colors.black),
children: <TextSpan>[
TextSpan(
text: '50% off',
style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: ' the price & early access. !'),
],
),
),
const SizedBox(
height: 20,
),
const Text(
'You can look forward to more teachers and practices very soon.'),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () => Navigator.pop(context),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
fixedSize: const Size(double.maxFinite, 50)),
child: const Text('Got it'),
),
],
),
),
);
}
Result Screen->

Not able to get element index in a listview - Flutter

i'm trying to make operations on clicked elements in a listView in flutter. An alertDialog should appear once I click an element so I can update its value. My backend works perfectly using the put http method. The problem is that i'm able to read the input value in console but not able to read the index of the clicked element.
As it's mentionned above, i'm able to read the input value which means that my api works correctly, but not able to retrieve the clicked element's index in the listView.
Console output:
I/flutter ( 4120): ============================== null
I/flutter ( 4120): 33
here is my update function:
handleMeasurement(String iv_id, String value) async {
final response = await http.put(
Uri.parse('${baseUrl}/api/v1/measurements/update/' + iv_id),
body: <String, String>{
"input_value": value
});
}
and here is my ui:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
'Traitement des mesures',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: Visibility(
visible: isLoaded,
replacement: Center(child: CircularProgressIndicator()),
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
padding: EdgeInsets.all(15),
itemCount: mesures?.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Mesure'),
content: TextField(
controller: _textFieldController,
decoration:
InputDecoration(hintText: "Entrez la valeur"),
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => {
print(
"============================== ${mesures![index].measurement_id}"),
print(_textFieldController.text),
handleMeasurement(
"${mesures![index].measurement_id}",
_textFieldController.text),
Navigator.pop(context, 'OK')
},
child: const Text('OK'),
),
],
),
),
child: Container(
margin: EdgeInsets.only(bottom: 15),
child: Row(
children: [
SizedBox(
width: 70,
child: AspectRatio(
aspectRatio: 0.88,
child: Container(
decoration: BoxDecoration(
color: Color(0xFFF5F6F9),
borderRadius: BorderRadius.circular(15),
),
child: Image.asset(
'assets/note2.png',
),
),
),
),
SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Paramètre: ${mesures![index].param_name}",
style: TextStyle(
color: Colors.black, fontSize: 16),
maxLines: 2,
),
SizedBox(height: 10),
Text.rich(
TextSpan(
text:
"Description: ${mesures![index].description}",
style: TextStyle(
fontWeight: FontWeight.w600,
color: kPrimaryColor),
),
),
],
),
],
),
),
);
},
),
)
],
),
),
);
}
Can anyone help me out with it? thanks in advance!

How can I change the height of CupertinoNavigationBar in Flutter?

I want to increase CupertinoNavigationBar heigth. The code is like this:
child: CustomCupertinoNavigationBar(
padding: EdgeInsetsDirectional.zero,
backgroundColor: Colors.white,
middle: Semantics(
label: "dashboard-main-page-title",
child: Text(
"My Title",
style: TextStyles.HankenSans_Bold_18_PrimaryBlack,
key: Key('dashboard-main-page-title'),
),
),
leading: Semantics(
label: "dashboard-back-button",
child: Material(
color: Colors.white,
child: CustomBackButton(
onPressHandler: () {
Navigation().openMyAccountPage();
},
),
),
),
);
I tried creating my own custom cupertino. I copied the cupertino/nav_bar.dart and changed _kNavBarPersistentHeight parameter as const double _kNavBarPersistentHeight = 58.0; but it resulted at two navigation bars in IOS. Can anybody help me with this? Much appreciated.
I solved this problem as
appBar: PreferredSize(
preferredSize: Size.fromHeight(100.0),
child: Container(
height: 120,
child: CupertinoNavigationBar(
padding: EdgeInsetsDirectional.zero,
backgroundColor: Colors.white,
middle: Semantics(
label: "dashboard-main-page-title",
child: Text(
CustomerLoyaltyLocalizations.instance.dashboardMainPageTitle,
style: TextStyles.HankenSans_Bold_18_PrimaryBlack,
key: Key('dashboard-main-page-title'),
),
),
leading: Semantics(
label: "dashboard-back-button",
child: Material(
color: Colors.white,
child: CustomBackButton(
onPressHandler: () {
Navigation().openMyAccountPage();
},
),
),
),
),
),
),
First I used PreferredSize and then Container widget before CupertinoNavigationBar.

How to fix a non-null String must be provided to a Text widget

this is part of my code, I keep getting a non-null String must be provided to a Text widget.
Still new to flutter, so I'm not sure on how to fix this. I tried putting the ??"" on child: Text(myQuiz[0][i.toString()] but then it gave me an error on The method '[]' was called on null.
Receiver: null
Tried calling:
Widget optionButton(String k) {
return Padding(
padding: EdgeInsets.only(
top: 10
),
child: MaterialButton(
onPressed: () => checkAns(k),
child: Text(
myQuiz[1][i.toString()][k],
style: TextStyle(
color: Colors.black,
fontFamily: "Open Sans",
fontSize: 16.0,
),
maxLines: 1,
),
color: buttonColor[k],
minWidth: 200.0,
height: 45.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Color(0xffb0dab9))),
),
);
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text("You must finish this quiz :)"),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Scaffold(
appBar: AppBar(title: Text('Quiz'),backgroundColor: Color(0xffb0dab9)),
backgroundColor: Colors.yellow[100],
body: Container(
padding: EdgeInsets.all(50),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(20),
alignment: Alignment.center,
child: Text(myQuiz[0][i.toString()],
style: TextStyle(fontSize: 20.0, color: Colors.black),
),
),
AbsorbPointer(
absorbing: disableAnswer,
child: Container(
padding: EdgeInsets.only(top: 30),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
optionButton('a'),
optionButton('b'),
optionButton('c'),
optionButton('d'),
],
),
),
),
Container(
padding: EdgeInsets.only(top: 30),
alignment: Alignment.topCenter,
child: Center(
child: Text(
showTimer ,
style: TextStyle(
fontSize: 20.0,
),
),
),
),
],
),
),
),
)
);
}
}
It is because a null value is being provide to your Text widget
From your code.. one or more of the following is null and not a string
myQuiz[1][i.toString()][k]
showTimer
Try
...
#override
Widget build(BuildContext context) {
print(myQuiz[1][i.toString()][k]);
print(showTimer);
to find out which is the null value
Try this.
Text(
myQuiz[1]?[i?.toString()]?[k] ?? "Default Value",
style: TextStyle(
color: Colors.black,
fontFamily: "Open Sans",
fontSize: 16.0,
),
maxLines: 1,
),
Thanks for helping, I have found the answer, it was in the getRandom, as the json does not have a 0, so when the quiz runs and hit 0, it causes the error

adding ListView.builder

I'm trying to make the displayAccoutList() scrollable.
I've tried to use ListView but it didn't work. I'm thinking to use ListView.builder but I don't know how to create data for accountItems()
enter code here`import 'package:flutter/material.dart';
import 'app_drawer.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Accounts',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Account(),
);
}
}
class Account extends StatefulWidget {
#override
_AccountState createState() => _AccountState();
}
class _AccountState extends State<Account> {
Card topArea() =>
Card(
margin: EdgeInsets.all(10.0),
elevation: 1.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(50.0))),
child: Container(
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [Color(0xFFFF5722), Color(0xFFFF5722)])),
padding: EdgeInsets.all(5.0),
// color: Color(0xFF015FFF),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
onPressed: () {},
),
Text("Savings",
style: TextStyle(color: Colors.white, fontSize: 20.0)),
IconButton(
icon: Icon(
Icons.arrow_forward,
color: Colors.white,
),
onPressed: () {},
)
],
),
Center(
child: Padding(
padding: EdgeInsets.all(5.0),
child: Text(r"£ " "100,943.33",
style: TextStyle(color: Colors.white, fontSize: 24.0)),
),
),
SizedBox(height: 35.0),
],
)),
);
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: AppDrawer(),
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.grey, //change your color here
),
backgroundColor: Colors.white,
elevation: 0.0,
title: Text(
"Accounts",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.search,
color: Colors.grey,
),
onPressed: () {},
)
],
),
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
topArea(),
SizedBox(
height: 40.0,
child: Icon(Icons.refresh,
size: 35.0,
color: Color(0xFFFF5722),
),
),
displayAccoutList()
],
),
),
bottomNavigationBar: BottomAppBar(
elevation: 0.0,
child: Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
FlatButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 30.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
color: Color(0xFFFF5722),
// borderSide: BorderSide(color: Color(0xFF015FFF), width: 1.0),
onPressed: () {},
child: Text("ACTIVITY"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("STATEMENTS"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("DETAILS"),
)
],
),
),
)
);
}
}
Container accountItems(String item, String charge, String dateString,
String type,
{Color oddColour = Colors.white}) =>
Container(
decoration: BoxDecoration(color: oddColour),
padding:
EdgeInsets.only(top: 20.0, bottom: 20.0, left: 5.0, right: 5.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(item, style: TextStyle(fontSize: 16.0)),
Text(charge, style: TextStyle(fontSize: 16.0))
],
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(dateString,
style: TextStyle(color: Colors.grey, fontSize: 14.0)),
Text(type, style: TextStyle(color: Colors.grey, fontSize: 14.0))
],
),
],
),
);
displayAccoutList() {
return Container(
margin: EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
accountItems("M KING", r"+ £ 4,946.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Gordon Street Tenants", r"+ £ 5,428.00", "15-07-19", "Credit"),
accountItems("Amazon EU", r"+ £ 746.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Floww LTD", r"+ £ 5,526.00", "15-07-19", "Credit"),
accountItems(
"KLM", r"- £ 2,500.00", "10-07-19", "Payment",
oddColour: const Color(0xFFF7F7F9)),
],
),
);
`
The other page app_drawer.dart
`
import 'package:flutter/material.dart';
class AppDrawer extends StatefulWidget {
#override
_AppDrawerState createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
#override
Widget build(BuildContext context) {
return SizedBox(
width: 160.0,
child: Drawer(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 50.0),
child: FlatButton.icon(
icon: Icon(
Icons.arrow_back,
color: Colors.grey,
),
onPressed: null,
label: Text("Back",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 16.0,
color: Colors.black)),
color: Colors.black,
),
),
buildMenuItem(Icons.account_balance, "ACCOUNTS",
opacity: 1.0, color: Color(0xFFFF6E40)),
Divider(),
buildMenuItem(Icons.compare_arrows, "TRANSFER"),
Divider(),
buildMenuItem(Icons.receipt, "STATEMENTS"),
Divider(),
buildMenuItem(Icons.attach_money, "PAYMENTS"),
Divider(),
buildMenuItem(Icons.sentiment_satisfied, "INVESTMENTS"),
Divider(),
buildMenuItem(Icons.phone, "SUPPORT"),
Divider()
],
),
),
);
}
Opacity buildMenuItem(IconData icon, String title,
{double opacity = 0.3, Color color = Colors.black}) {
return Opacity(
opacity: opacity,
child: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 20.0,
),
Icon(
icon,
size: 50.0,
color: color,
),
SizedBox(
height: 10.0,
),
Text(title,
style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 14.0, color: color)),
SizedBox(
height: 10.0,
),
],
),
),
);
}
}
`
To able to scroll through the section and have unlimited amount of transaction
I think this is what you are going for.
In this snippet, I defined Language as a class with attributes language and rating.
Then I created a list of languages in the stateless widget TheList.
Finally, I used the listView.builder to map the list for its length and display text that shows the attributes of the languages.
Let me know if you have any questions!
import 'package:flutter/material.dart';
class Language {
const Language({this.language,this.rating});
final String language;
final String rating;
}
class TheList extends StatelessWidget {
// Builder methods rely on a set of data, such as a list.
final List<Language> _languages = [
const Language(language: "flutter", rating: "amazing"),
const Language(language: "javascript", rating: "stellar"),
const Language(language: "java", rating: "sucks"),
];
// First, make your build method like normal.
// Instead of returning Widgets, return a method that returns widgets.
// Don't forget to pass in the context!
#override
Widget build(BuildContext context) {
return _buildList(context);
}
// A builder method almost always returns a ListView.
// A ListView is a widget similar to Column or Row.
// It knows whether it needs to be scrollable or not.
// It has a constructor called builder, which it knows will
// work with a List.
ListView _buildList(context) {
return ListView.builder(
// Must have an item count equal to the number of items!
itemCount: _languages.length,
// A callback that will return a widget.
itemBuilder: (context, index) {
// In our case, a Language and its rating for each language in the list.
return Text(_languages[index].language + ": " + _languages[index].rating);
},
);
}
}