It is not accepted to change the value in the Dropdown in the bottom sheet? - flutter

Flutter . It is not accepted to change the value in the Dropdown in the bottom sheet ?
I made all the changes and it didn't work !
Knowing that on a normal screen it works
please help me
class _AddPostState extends State<AddPost> {
List<DropdownMenuItem<String>> get itemse{
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(
value: '1',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(width: 15,),
Icon(Icons.lock_outline,size: 19,),
SizedBox(width: 10,),
Text('Only me'),
],
),
),
),
DropdownMenuItem(
value: '2',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(width: 15,),
Icon(Icons.group_rounded,size: 19,),
SizedBox(width: 10,),
Text('Friends'),
],
),
),
),
DropdownMenuItem(
value: '3',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(width: 15,),
Icon(Icons.public,size: 19,),
SizedBox(width: 10,),
Text('Public'),
],
),
),
),
];
return menuItems;
}
String? selectedValue = '1';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
foregroundColor: Colors.black,
backgroundColor: Colors.white,
title: const Text('Add Post'),
),
body: Center(
child: ElevatedButton(
child: const Text('Open'),
onPressed: bottomSheet,
),
),
);
}
void bottomSheet(){
showCupertinoModalBottomSheet(
expand: true,
context: context,
backgroundColor: Colors.transparent,
builder: (context) =>Scaffold(
appBar: AppBar(backgroundColor: Colors.white,foregroundColor: Colors.black,),
body: Column(
children: [
DropdownButton(
value: selectedValue,
items: itemse,
onChanged: (y) {
setState(() {
selectedValue = y! as String;
});
},
)
],
),
),
);
}
}
Seven days, I searched for a solution to the problem and did not find the solution. Please help

From the code i see you are not using the StatefulBuilder which will rebuild the sheet and change your value. From the code that you provided i have just created and example for you which might help you.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.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 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> {
List<DropdownMenuItem<String>> get itemse {
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(
value: '1',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(
width: 15,
),
Icon(
Icons.lock_outline,
size: 19,
),
SizedBox(
width: 10,
),
Text('Only me'),
],
),
),
),
DropdownMenuItem(
value: '2',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(
width: 15,
),
Icon(
Icons.group_rounded,
size: 19,
),
SizedBox(
width: 10,
),
Text('Friends'),
],
),
),
),
DropdownMenuItem(
value: '3',
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: const [
SizedBox(
width: 15,
),
Icon(
Icons.public,
size: 19,
),
SizedBox(
width: 10,
),
Text('Public'),
],
),
),
),
];
return menuItems;
}
String? selectedValue = '1';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
foregroundColor: Colors.black,
backgroundColor: Colors.white,
title: const Text('Add Post'),
),
body: Center(
child: ElevatedButton(
child: const Text('Open'),
onPressed: bottomSheet,
),
),
);
}
void bottomSheet() {
showCupertinoModalBottomSheet(
expand: true,
context: context,
backgroundColor: Colors.transparent,
builder: (context) =>
StatefulBuilder(builder: (BuildContext context, StateSetter setState /*You can rename this!*/) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
),
body: Column(
children: [
DropdownButton(
value: selectedValue,
items: itemse,
onChanged: (y) {
setState(() {
selectedValue = y! as String;
});
},
)
],
),
);
}),
);
}
}

Related

Flutter:How can i change the color of selected menu item from drawer

I am creating an app in flutter, I have got some issue in drawer. I want to change the color of the selected drawer item.Here is my full code it looks fine to me but its not working for me... please help me find out what i am doing wrong
class _DrawerClassState extends State<DrawerClass> {
Here is my full code it looks fine to me but its not working for me... please help me find out what i am doing wrong
List<String> menuStrings = [
'HOME',
'NOTIFICATIONS',
'PARTNERS',
'LOCATIONS',
'FEEDBACK',
'CONTACT US',
'AWARDS'
];
Here is my full code it looks fine to me but its not working for me... please help me find out what i am doing wrong
List menuScreens = [
HomeScreen(),
Notifications(),
Partners(),
Locations(),
FeedbackScreen(),
const ContactUs(),
Awards()
];
Here is my full code it looks fine to me but its not working for me... please help me find out what i am doing wrong
List<bool> isHighlighted = [false, false, false, false, true, false, false];
#override
Widget build(BuildContext context) {
return Theme(
data: Theme.of(context).copyWith(
canvasColor: Colors.black,
),
child: Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
drawerTop("HI USER"),
ListView.builder(
shrinkWrap: true,
itemCount: menuScreens.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
for (int i = 0; i < isHighlighted.length; i++) {
setState(() {
if (index == i) {
isHighlighted[index] = true;
} else {
//the condition to change the highlighted item
isHighlighted[i] = false;
}
});
}
},
child: drawerItems(
context,
menuStrings[index],
menuScreens[index],
isHighlighted[index] ? Colors.amber : Colors.white,
),
);
},
),
],
),
),
);
}
}
Here is the method drawerItems() to build drawer items
drawerItems(BuildContext context, String title, path, Color color) {
return Padding(
padding: EdgeInsets.only(
top: 0.0, left: MediaQuery.of(context).size.width * 0.1),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
GestureDetector(
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: ((context) => path)));
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
title,
style: TextStyle(
color: color,
fontFamily: "Raleway Reg",
fontSize: 23,
letterSpacing: 2),
),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
child: const Divider(
thickness: 1,
color: Colors.white,
height: 3,
),
),
]));
}
Update your drawerItems
drawerItems(BuildContext context, String title, path, Color color) {
return Container(
color: color,
padding: EdgeInsets.only(
top: 0.0, left: MediaQuery.of(context).size.width * 0.1),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
GestureDetector(
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: ((context) => path)));
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
title,
style: TextStyle(
color: color,
fontFamily: "Raleway Reg",
fontSize: 23,
letterSpacing: 2),
),
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
child: const Divider(
thickness: 1,
color: Colors.white,
height: 3,
),
),
]));
}
the root widget that is returned from the method, change it from Padding to Container and give it a color
I think it's a very complex solution to solve this simple task in Flutter.
I suggest my solution:
Publish it on my git:
https://github.com/igdmitrov/flutter-drawer
Create a new Abstract Page State:
abstract class MyPageState<T extends StatefulWidget> extends State {
List<Widget> drawerItems(BuildContext context) {
return menuItems
.map(
(item) => ListTile(
leading: const Icon(Icons.my_library_books),
title: Text(
item['menuName'] as String,
style: TextStyle(
color: isHighlighted[menuItems.toList().indexOf(item)]
? Colors.amber
: Colors.grey),
),
onTap: () {
isHighlighted = isHighlighted.map((mark) => false).toList();
isHighlighted[menuItems.toList().indexOf(item)] = true;
Navigator.of(context).push(MaterialPageRoute(
builder: ((context) => item['route'] as Widget)));
},
),
)
.toList();
}
}
Create drawer.dart file with code:
final menuItems = {
{'menuName': 'HOME', 'route': const HomeScreen()},
{'menuName': 'NOTIFICATIONS', 'route': const Notifications()},
};
List<bool> isHighlighted = [false, false];
And create pages:
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
MyPageState<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends MyPageState<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Main page'),
),
drawer: Drawer(
child: ListView(
children: [
const Text("HI USER"),
...drawerItems(context),
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'New app',
),
],
),
),
);
}
}
And Notifications page:
class Notifications extends StatefulWidget {
static String routeName = '/notifications';
const Notifications({Key? key}) : super(key: key);
#override
MyPageState<Notifications> createState() => _NotificationsState();
}
class _NotificationsState extends MyPageState<Notifications> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Notifications'),
),
drawer: Drawer(
child: ListView(
children: [
const Text("HI USER"),
...drawerItems(context),
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'Notifications page',
),
],
),
),
);
}
}

Custom Sliver App Bar in flutter with an Image and 2 Text widgets going into app bar on scrolling

i want to implement the sliver app bar as shown in the the 2 pictures given below. After much googling , I fount about the CustomScrollView widget and the SliverAppBar widget but all the tutorials and blogs online about sliver app bars show a simple one where an image disappears into an app bar with a text as title on scrolling. However here what I want to achieve is slightly different and I am having a hard time trying to figure out how to do it. Can anyone help me with it?
You can try this:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ScrollController? _scrollController;
bool lastStatus = true;
double height = 200;
void _scrollListener() {
if (_isShrink != lastStatus) {
setState(() {
lastStatus = _isShrink;
});
}
}
bool get _isShrink {
return _scrollController != null &&
_scrollController!.hasClients &&
_scrollController!.offset > (height - kToolbarHeight);
}
#override
void initState() {
super.initState();
_scrollController = ScrollController()..addListener(_scrollListener);
}
#override
void dispose() {
_scrollController?.removeListener(_scrollListener);
_scrollController?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
title: 'Horizons Weather',
home: Scaffold(
body: NestedScrollView(
controller: _scrollController,
headerSliverBuilder: (context, innerBoxIsScrolled) {
return [
SliverAppBar(
elevation: 0,
backgroundColor: Colors.blueGrey,
pinned: true,
expandedHeight: 275,
flexibleSpace: FlexibleSpaceBar(
collapseMode: CollapseMode.parallax,
title: _isShrink
? const Text(
"Profile",
)
: null,
background: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 48),
child: ClipRRect(
borderRadius: BorderRadius.circular(100),
child: Image.network(
headerImage,
fit: BoxFit.cover,
height: 100,
width: 100,
),
),
),
const SizedBox(
height: 16,
),
Text(
"Flipkart",
style: textTheme.headline4,
),
const SizedBox(
height: 8,
),
const Text(
"flipkart.com",
),
const SizedBox(
height: 5,
),
const Text(
"Info about the company",
),
],
),
),
),
actions: _isShrink
? [
Padding(
padding: const EdgeInsets.only(left: 8, right: 12),
child: Row(
children: [
Padding(
padding:
const EdgeInsets.only(left: 8, right: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
"Flipkart",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
Text(
"flipkart.com",
style: TextStyle(
fontSize: 12,
),
),
],
),
),
ClipRRect(
borderRadius: BorderRadius.circular(100),
child: Image.network(
headerImage,
fit: BoxFit.cover,
height: 30,
width: 30,
),
),
],
),
),
]
: null,
),
];
},
body: CustomScrollView(
scrollBehavior: const ConstantScrollBehavior(),
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Center(child: Text("Item: $index")),
);
},
childCount: 50,
),
),
],
),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
const UserAccountsDrawerHeader(
accountName: Text("Zakaria Hossain"),
accountEmail: Text("zakariaaltime#gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.orange,
child: Text(
"A",
style: TextStyle(fontSize: 40.0),
),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text("Home"),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.contacts),
title: Text("Contact Us"),
onTap: () {
Navigator.pop(context);
},
),
],
),
),
),
);
}
}
Demo

I am getting two appBar in flutter app. I am trying to add Drawer widget and TabBar widget in flutter app

main.dart
import 'package:flutter/material.dart';
import 'package:stray_animal_emergencyrescue/signUpPage.dart';
import './commons/commonWidgets.dart';
import 'package:stray_animal_emergencyrescue/loggedIn.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: 'Flutter login UI',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//String showPasswordText = "Show Password";
bool obscurePasswordText = true;
#override
Widget build(BuildContext context) {
final passwordField = TextField(
obscureText: obscurePasswordText,
decoration: InputDecoration(
//contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintText: "Password",
//border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
suffixIcon: IconButton(
icon: new Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
this.obscurePasswordText = !obscurePasswordText;
});
},
)),
);
final loginButon = Material(
//elevation: 5.0,
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LogIn()),
);
},
child: Text('Login', textAlign: TextAlign.center),
),
);
final facebookContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Facebook', textAlign: TextAlign.center),
),
);
final googleContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Google ', textAlign: TextAlign.center),
),
);
final signUpButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => FormScreen()),
);
//print(MediaQuery.of(context).size.width);
},
child: Text('Sign Up ', textAlign: TextAlign.center),
),
);
return Scaffold(
appBar: AppBar(
title: Text("Animal Emergency App"),
),
body: Center(
child: Container(
//color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//SizedBox(height: 45.0),
getTextFieldWidget(),
SizedBox(height: 15.0),
passwordField,
sizedBoxWidget,
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
facebookContinueButton,
SizedBox(width: 5),
googleContinueButton,
SizedBox(width: 5),
loginButon
],
),
/*loginButon,
signUpButton,*/
sizedBoxWidget,
const Divider(
color: Colors.black,
height: 20,
thickness: 1,
indent: 20,
endIndent: 0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
signUpButton
],
),
],
),
),
),
),
);
}
}
loggedIn.dart
import 'package:flutter/material.dart';
import './tabbarviews/emergencyresue/EmergencyHome.dart';
import './tabbarviews/animalcruelty/animalCrueltyHome.dart';
import './tabbarviews/bloodbank/bloodBankHome.dart';
class LogIn extends StatefulWidget {
#override
_LogInState createState() => _LogInState();
}
class _LogInState extends State<LogIn> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions = <Widget>[
EmergencyHome(),
AnimalCrueltyHome(),
BloodBankHome()
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First app bar appearing'),
actions: <Widget>[
GestureDetector(
onTap: () {},
child: CircleAvatar(
//child: Text("SC"),
backgroundImage: AssetImage('assets/images/760279.jpg'),
//backgroundImage: ,
),
),
IconButton(
icon: Icon(Icons.more_vert),
color: Colors.white,
onPressed: () {},
),
],
),
drawer: Drawer(
child: ListView(
children: <Widget>[
new ListTile(title: Text("Primary")),
MyListTile(
"Home",
false,
"Your customized News Feed about people you follow, ongoing rescues, nearby activities, adoptions etc.",
3,
Icons.home,
true,
() {}),
MyListTile(
"News & Media Coverage",
false,
"News about incidents which need immediate action, changing Laws",
3,
Icons.home,
false,
() {}),
MyListTile(
"Report",
true,
"Report cases with evidences anonymously",
3,
Icons.announcement,
false,
() {}),
MyListTile(
"Blood Bank",
true,
"Details to donate blood ",
3,
Icons.medical_services,
false,
() {}),
],
),
),
body: _widgetOptions[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.pets),
label: 'Emergency Rescue',
),
BottomNavigationBarItem(
icon: Icon(Icons.add_alert),
label: 'Report Cruelty',
),
BottomNavigationBarItem(
icon: Icon(Icons.medical_services),
label: 'Blood Bank',
),
/*BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'Safe Hands',
backgroundColor: Colors.blue),*/
],
onTap: _onItemTapped,
),
);
}
}
//Safe Hands
class MyListTile extends StatelessWidget {
final String title;
final bool isThreeLine;
final String subtitle;
final int maxLines;
final IconData icon;
final bool selected;
final Function onTap;
MyListTile(this.title, this.isThreeLine, this.subtitle, this.maxLines,
this.icon, this.selected, this.onTap);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(title),
isThreeLine: isThreeLine,
subtitle:
Text(subtitle, maxLines: maxLines, style: TextStyle(fontSize: 12)),
leading: Icon(icon),
selected: selected,
onTap: onTap);
}
}
EmergencyHome.dart
import 'package:flutter/material.dart';
import './finishedAnimalEmergencies.dart';
import './reportAnimalEmergency.dart';
import './ongoingAnimalEmergencies.dart';
class EmergencyHome extends StatefulWidget {
#override
_EmergencyHomeState createState() => _EmergencyHomeState();
}
class _EmergencyHomeState extends State<EmergencyHome> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Second appBar appearing"),
bottom: TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
}
}
The issue I am facing is two appBar, I tried removing appBar from loggedIn.dart but Drawer hamburger icon is not showing, and I cannot remove appBar from emergencyHome.dart as I wont be able to add Tab bar. What is viable solution for this? Please help how to Structure by app and routes to easily manage navigation within app
Remove the appbar from EmergencyHome.dart
this will remove the second app title. But there will be that shadow from the first app bar so put elvation:0
so, this will look like one appbar now your drawer will also work.
you can use flexibleSpace in EmergencyHome.dart
DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
flexibleSpace: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
You don't want to make two appbar to get the drawer property. Use DefaultTabController then inside that you can use scaffold.so, you can have drawer: Drawer() inside that you can also get a appbar with it with TabBar as it's bottom.
This is most suitable for you according to your use case.
i will put the full code below so you can copy it.
void main() {
runApp(const TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
const TabBarDemo({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
drawer: Drawer(),
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(
text: "report",
),
Tab(text: "ongoing"),
Tab(text: "completed"),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
OUTPUT

TextEditController clears the text field's text

I am trying to make an application about to do. But there is an issue. I write some text to the text field. But When I add a new text field it clears the text filed's text. And when I delete the TextEditingController it fixes the issue. But then when I try to slide it right or left it clears the text again.
Here is the code
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
void main() => runApp(MaterialApp(
home: Home(),
));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int today=1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("Takveam"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
"$today",
style: TextStyle(
fontSize: 20.0,
color: Colors.lightGreenAccent[700],
letterSpacing: 1,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Todo()),
);
},
icon: Icon(Icons.featured_play_list),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today-=1;
if(today<1)
today=31;
});
},
icon: Icon(Icons.calendar_today),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today=31;
});
},
icon: Icon(Icons.access_alarms),
color: Colors.lightGreenAccent[700],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
today+=1;
if(today>31)
{
today=1;
}
});
},
child: Text("Dıkla"),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
class Todo extends StatefulWidget {
#override
_TodoState createState() => _TodoState();
}
class _TodoState extends State<Todo> {
int i=1;
List<Column> todoos = [
Column(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("To do"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: ListView.builder(
itemCount: i,
itemBuilder: (context,index){
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
height: 60,
child: Card(
color: Colors.lightGreenAccent[700],
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
controller: new TextEditingController(),
style: TextStyle(
fontSize: 20,
color: Colors.white
),
onChanged: (text) {
print(i);
},
),
],
),
),
),
actions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.check_circle,
)
],
secondaryActions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.more_horiz
)
],
),
],
);
}
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
i+=1;
});
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
You can copy paste run full code below
Each item need a TextEditingController
For demo purpose, I remove background color
Step 1: declare a List<TextEditingController> listTexttCtrl = [TextEditingController()];
Step 2: In FloatingActionButton, add listTexttCtrl.add(TextEditingController());
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
i += 1;
listTexttCtrl.add(TextEditingController());
});
},
Step 3: TextField controller attribute use listTexttCtrl[index]
TextField(
controller: listTexttCtrl[index],
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
void main() => runApp(MaterialApp(
home: Home(),
));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int today = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("Takveam"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
"$today",
style: TextStyle(
fontSize: 20.0,
color: Colors.lightGreenAccent[700],
letterSpacing: 1,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Todo()),
);
},
icon: Icon(Icons.featured_play_list),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today -= 1;
if (today < 1) today = 31;
});
},
icon: Icon(Icons.calendar_today),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today = 31;
});
},
icon: Icon(Icons.access_alarms),
color: Colors.lightGreenAccent[700],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
today += 1;
if (today > 31) {
today = 1;
}
});
},
child: Text("Dıkla"),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
class Todo extends StatefulWidget {
#override
_TodoState createState() => _TodoState();
}
class _TodoState extends State<Todo> {
int i = 1;
List<Column> todoos = [
Column(),
];
List<TextEditingController> listTexttCtrl = [TextEditingController()];
#override
Widget build(BuildContext context) {
return Scaffold(
//backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("To do"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: ListView.builder(
itemCount: i,
itemBuilder: (context, index) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
height: 60,
child: Card(
color: Colors.lightGreenAccent[700],
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
controller: listTexttCtrl[index],
style: TextStyle(fontSize: 20, color: Colors.white),
onChanged: (text) {
print(i);
},
),
],
),
),
),
actions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.check_circle,
)
],
secondaryActions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.more_horiz)
],
),
],
);
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
i += 1;
listTexttCtrl.add(TextEditingController());
});
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}

Theme Data not applying in inherited classes

I have declared a theme in main.dart , and it works fine as long as the context is used in main.dart but when I use Theme.of(context).primaryColor in the child class context doesn't pickup the theme.
Main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Expenso',
theme: ThemeData(
primarySwatch: Colors.green,
accentColor: Colors.amber
),
home: Expenso(),
);
}
}
class Expenso extends StatefulWidget {
#override
_ExpensoState createState() => _ExpensoState();
}
class _ExpensoState extends State<Expenso> {
final List<Transaction> _transactions=[
];
void _addTransaction(String txTitle,double txAmount)
{
final newTx=Transaction(
title: txTitle,
amount: txAmount,
id: DateTime.now().toString(),
date: DateTime.now()
);
setState(() {
_transactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor:Theme.of(context).primaryColor,
title: Text('Expenso'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
)
],
),
body:SingleChildScrollView(
child: Column(
//mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
width: double.infinity,
height: 50,
child: Card(
color: Colors.blue,
child: Text('chart')
)
),
TransactionList(_transactions)
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed:() => _startAddNewTransaction(context),
backgroundColor: Theme.of(context).accentColor,
),
)
);
}
}
transaction_list.dart
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> tractn;
TransactionList(this.tractn);
#override
Widget build(BuildContext context) {
return Container(
height: 500,
child :tractn.isEmpty? Column(
children: <Widget>[
Text('No Transaction added yet'),
SizedBox(
height: 20,
),
Container(
height:300,
child: Image.asset('assets/Images/waiting.png',
fit: BoxFit.cover,),
)
],
): ListView.builder(
itemBuilder: (ctx,index){
return Card(
child: Row(
children: <Widget>[
Container(
margin: EdgeInsets.symmetric(
vertical: 10,
horizontal: 15,
),
decoration: BoxDecoration(border: Border.all(
color: Theme.of(context).primaryColor,
width: 2,
style: BorderStyle.solid
)
),
padding: EdgeInsets.all(10),
child: Text(
'₹ ${tractn[index].amount.toStringAsFixed(2)}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic ,
fontSize: 20,
color: Colors.green,
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
tractn[index].title,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Theme.of(context).primaryColor
),
),
Text(
DateFormat().format(tractn[index].date) ,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.grey
),),
Text(
tractn[index].id
)
],
)
],
),
);
},
itemCount: tractn.length,
)
);
}
}
Please guide me the way to implement the theme in inherited classes
I Agree with #Nolence comment.
If you are expecting to achieve the below result
Remove MaterialApp widget and make Scaffold as your primate return widget inside
class _ExpensoState
Sample Code:
import 'package:flutter/material.dart';
import 'package:flutter_app/Transaction.dart';
import 'transaction_list.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Expenso',
theme: ThemeData(
primarySwatch: Colors.green,
accentColor: Colors.amber
),
home: Expenso(),
);
}
}
class Expenso extends StatefulWidget {
#override
_ExpensoState createState() => _ExpensoState();
}
class _ExpensoState extends State<Expenso> {
final List<Transaction> _transactions=[
];
void _addTransaction(String txTitle,double txAmount)
{
final newTx=Transaction(
title: txTitle,
amount: txAmount,
id: DateTime.now().toString(),
date: DateTime.now()
);
setState(() {
_transactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor:Theme.of(context).primaryColor,
title: Text('Expenso'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
)
],
),
body:SingleChildScrollView(
child: Column(
//mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
width: double.infinity,
height: 50,
child: Card(
color: Colors.blue,
child: Text('chart')
)
),
TransactionList(_transactions)
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed:() => _startAddNewTransaction(context),
backgroundColor: Theme.of(context).accentColor,
),
);
}
}
If this is not what you wanted, please elaborate your question or comment below.
In the build method of your Expenso widget you define another MaterialApp, which creates its own default theme (different to your first theme). Remove that MaterialApp widget and it should work.