Problem in multilingualizing the app in flutter - flutter

I encountered a problem in making my app multilingual.
On the other pages of my app, when the code
S.of(context).myText is called, the code works correctly and And the text corresponding to the language chosen by the audience is displayed, but on the one class of my app named Home, by calling this program code, regardless of the selected language, only the English text is displayed shows even if I choose Malaysia or Arabic.
Interestingly, when I build the project with Chrome, there is no problem, but when I download the apk from it, it does not work on the mobile.
the problem is with S.of(context).Home_drawer_mainMenu, in below code:
my Home class:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:untitled22/SignUp.dart';
import 'package:untitled22/TabBarViewHome.dart';
import 'package:untitled22/loginFile.dart';
import './Page_1.dart';
import './Page_2.dart';
import './Page_3.dart';
import './Page_4.dart';
import 'LanguageChangeProvider.dart';
import 'package:untitled22/generated/l10n.dart';
void main() {
runApp(const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int pageNumb = 0;
late TabController _controller;
String _currentLanguage = 'ar';
bool rtl = false;
#override
void initState() {
_loadCounter();
super.initState();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_currentLanguage = (prefs.getString('currentLang') ?? '');
rtl = (prefs.getBool('isRtl') ?? false);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
locale: new Locale(_currentLanguage),
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
home: BodyBody(),
debugShowCheckedModeBanner: false,
showSemanticsDebugger: false,
);
}
}
class BodyBody extends StatefulWidget {
const BodyBody({Key? key}) : super(key: key);
#override
State<BodyBody> createState() => _BodyBodyState();
}
class _BodyBodyState extends State<BodyBody> with SingleTickerProviderStateMixin {
int pageNumb = 0;
late TabController _controller;
String _currentLanguage = '';
bool rtl = false;
#override
void initState() {
_loadCounter();
super.initState();
_controller = TabController(vsync: this, length: 3, initialIndex: 1);
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_currentLanguage = (prefs.getString('currentLang') ?? 'ar');
rtl = (prefs.getBool('isRtl') ?? false);
});
}
#override
Widget build(BuildContext context) {
Size media = MediaQuery.of(context).size;
var height = AppBar().preferredSize.height;
TextEditingController textController = TextEditingController();
return DefaultTabController(
initialIndex: 1,
length: 3,
child: Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: Text(
S.of(context).Home_drawer_mainMenu,
style: TextStyle(
color: Color(0xFF434343),
fontSize: rtl == true ? 16 : 14,
),
),
backgroundColor: const Color(0xff26c6da),
leading: Builder(
builder: (BuildContext context) {
return Container(
child: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openDrawer();
},
color: const Color(0xFF434343),
),
);
},
),
actions: <Widget>[
IconButton(
onPressed: () {
print(height);
},
icon: Icon(Icons.search),
padding: rtl == false ? const EdgeInsets.only(right: 10) : const EdgeInsets.only(left: 10),
color: const Color(0xFF434343),
),
IconButton(
onPressed: () {},
icon: Icon(Icons.settings),
padding: rtl == false ? const EdgeInsets.only(right: 15) : const EdgeInsets.only(left: 15),
color: const Color(0xFF434343),
),
],
bottom: TabBar(
controller: _controller,
labelColor: Color(0xff434343),
unselectedLabelColor: Color(0xff434343),
indicatorColor: Color(0xff434343),
automaticIndicatorColorAdjustment: false,
tabs: <Widget>[
Tab(
icon: Icon(Icons.event_note_outlined),
),
Tab(
icon: Icon(Icons.home_rounded),
),
Tab(
icon: Icon(Icons.add_alert),
),
],
),
),
body: TabBarView(
controller: _controller,
children: [
TabBarHome(width: media.width, height: media.height),
TabBarHome(width: media.width, height: media.height),
TabBarHome(width: media.width, height: media.height),
],
),
drawer: Drawer(
child: ListView(
children: [
GestureDetector(
onTap: () {
print('hey');
},
child: InkWell(
onTap: () {},
child: Container(
color: Colors.grey.shade100,
height: media.height * 0.2,
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
height: 70,
width: 90,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.fitWidth,
image: AssetImage("images/aga.png"),
)),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
"Text",
style: TextStyle(
fontSize: 17,
color: Colors.black87,
fontWeight: FontWeight.w600,
),
),
Text(
"The best leader",
textAlign: TextAlign.justify,
style: TextStyle(
fontSize: 15,
color: Colors.black87,
),
),
],
),
],
),
Container(
child: rtl == true ? Icon(Icons.keyboard_arrow_right_rounded) : Icon(Icons.keyboard_arrow_left_rounded),
),
],
),
),
),
),
),
),
Padding(
padding: EdgeInsets.all(10),
child: Text(
S.of(context).Home_drawer_mainMenu,
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text('data'),
),
ListTile(
leading: Icon(Icons.add_call),
title: Text('call with us'),
),
],
),
),
),
);
}
}

Related

Flutter selected product becomes unselected after switching pages

I am building an online bottle store app using flutter and I am having an issue where if I add a product to favorites the selected product's button won't stay selected on the home page if I switch pages. I have categorized the products using a Tabbar and Tabbarview. I have tried using AutomaticKeepAliveClientMxin to keep the page alive but with no success. Please can anyone assist.
Here's what happens:
I click on the selected product
then it is added to Favorites
Come back to the home page and the selected item is no longer showing that it is selected
Here's my code:
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
ProductProvider productProvider = ProductProvider();
late TabController tabController;
#override
void initState() {
super.initState();
tabController = TabController(length: 4, vsync: this);
}
#override
void dispose() {
tabController.dispose();
super.dispose();
}
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
var cart = Provider.of<ShoppingCartProvider>(context);
var favoriteProvider = Provider.of<FavoriteProvider>(context);
Size _screenSize = MediaQuery.of(context).size;
final double itemHeight = (_screenSize.height - kToolbarHeight - 24) / 2;
final double itemWidth = _screenSize.width / 2;
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Categories',
style: TextStyle(
fontSize: 20.0,
fontFamily: 'Montserrat-ExtraBold',
fontWeight: FontWeight.bold),
),
),
Container(
child: Align(
alignment: Alignment.centerLeft,
child: TabBar(
controller: tabController,
indicator:
CircleTabIndicator(color: Colors.redAccent, radius: 4.0),
isScrollable: true,
labelColor: Colors.redAccent,
labelStyle: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
unselectedLabelColor: Colors.black,
unselectedLabelStyle: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
tabs: const [
Tab(text: 'Brandy'),
Tab(text: 'Gin'),
Tab(text: 'Soft drinks'),
Tab(text: 'Whiskey')
],
),
),
),
Container(
height: 400,
width: double.maxFinite,
child: TabBarView(
controller: tabController,
children: productProvider.categories.map((bottleCategory) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: itemWidth / itemHeight,
),
itemCount: bottleCategory.bottleList.length,
itemBuilder: (context, index) {
return Card(
shadowColor: Colors.grey,
surfaceTintColor: Colors.amber,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Stack(
children: [
Positioned(
right: 0,
child: InkWell(
onTap: () {
favoriteProvider.toggleFavorites(
bottleCategory.bottleList[index]);
if (favoriteProvider.isExist(
bottleCategory.bottleList[index])) {
ScaffoldMessenger.of(context)
.hideCurrentSnackBar();
ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text(
"Product Added to Favorite!",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.green,
duration: Duration(seconds: 1),
),
);
} else {
ScaffoldMessenger.of(context)
.hideCurrentSnackBar();
ScaffoldMessenger.of(context)
.showSnackBar(
const SnackBar(
content: Text(
"Product Removed from Favorite!",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.red,
duration: Duration(seconds: 1),
),
);
}
},
child: favoriteProvider.isExist(
bottleCategory.bottleList[index])
? const Icon(
Icons.favorite,
color: Colors.redAccent,
)
: const Icon(Icons.favorite_border),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset(
bottleCategory.bottleList[index].image,
height: 200.0,
),
),
Center(
child: Text(
bottleCategory
.bottleList[index].bottleName,
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold))),
Center(
child: Text(
'R${bottleCategory.bottleList[index].price}'),
)
],
),
Positioned(
bottom: 0,
right: 10,
child: IconButton(
icon: const Icon(Icons.add_circle),
iconSize: 40.0,
onPressed: () {
cart.addToCart(
bottleCategory.bottleList[index].id,
bottleCategory
.bottleList[index].bottleName,
bottleCategory
.bottleList[index].price,
bottleCategory
.bottleList[index].image);
},
))
],
),
);
},
);
}).toList()),
),
],
),
),
);
}
}
class FavoriteProvider with ChangeNotifier {
List<Bottle> _favItems = [];
List<Bottle> get favItems {
return [..._favItems];
}
void toggleFavorites(Bottle favBottle) {
final isExist = _favItems.contains(favBottle);
if (isExist) {
_favItems.remove(favBottle);
} else {
_favItems.add(favBottle);
}
notifyListeners();
}
bool isExist(Bottle favBottle) {
final isExist = _favItems.contains(favBottle);
return isExist;
}
void clearFavorite() {
_favItems = [];
notifyListeners();
}
}
Try using Consumer widget. Like so:
Consumer<favoriteProvider>(
builder: (BuildContext context, favorite, _){
return Icon(
Icons.favorite,
color: favorite.isExist(bottleCategory.bottleList[index])? Colors.redAccent : null,
);
},
),
Consumer widget will refresh or change the state whenever the ChangeNotifier of that model, in this case, FavoriteProvider is triggered, this should allows your widget to change and check itself anytime. So you shouldn't need to keep your state or screen alive all the time.
If that doesn't work, please change your Business Logic in the FavoriteProvider. Instead of using contains, I suggest to use any and identifies each instances with its own id or any of its unique variable. Like so:
bool isExist(Bottle favBottle) {
final isExist = _favItems.any((e) =>e.bottleName == favBottle.bottleName);
return isExist;
}

Flutter setState not updating values

Hi there a Flutter newbie here.
I have a project to be submitted via flutter. This is my main code and it's not updating text to stop when button was clicked.
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FM Mahanama',
theme: ThemeData(
primaryColor: const Color(0xfffbc02d),
primarySwatch: Colors.amber,
useMaterial3: true,
),
darkTheme: ThemeData(
primaryColor: const Color(0xfffbc02d),
primarySwatch: Colors.amber,
brightness: Brightness.dark,
useMaterial3: true,
),
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
home: const MyHomePage(title: 'FM Mahanama'),
);
}
}
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> {
int _selectedAppIndex = 0;
IconData iconPlayStop = Icons.play_arrow_rounded;
String txtPlayStop = "Play";
static final assetsAudioPlayer = AssetsAudioPlayer();
#override
void initState() {
WidgetsFlutterBinding.ensureInitialized();
initFirebaseActivities();
}
void initFirebaseActivities() {
Firebase.initializeApp();
}
static Future<void> initRadioPlayer(param0) async {
try {
await assetsAudioPlayer.open(
Audio.liveStream(param0),
showNotification: true,
autoStart: true,
);
} catch (t) {
AlertDialog(title: const Text("Error"), content: Text(t.toString()),);
}
}
void updateButtonText(String txt, IconData iconData){
setState(() {
txtPlayStop = txt;
iconPlayStop = iconData;
});
}
#override
void dispose() {
if(assetsAudioPlayer.isPlaying.value){
assetsAudioPlayer.stop();
}
}
static void _openFacebookPage() async {
String fbProtocolUrl = "fb://page/865683116816630";
String fallbackUrl = "https://www.facebook.com/mcrcofficial/";
try {
bool launched = await launchUrlString(fbProtocolUrl);
if (!launched) {
await launchUrlString(fallbackUrl);
}
} catch (e) {
await launchUrlString(fallbackUrl);
}
}
late final Set<Widget> _appPages = <Widget>{
Center(
child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection("public")
.doc("stream")
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> data) {
if (data.hasData) {
if (!data.data?.get("onair")) {
if (assetsAudioPlayer.isPlaying.value) {
assetsAudioPlayer.stop();
}
}
return Visibility(
replacement: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 20.0),
child: Image.asset(
"assets/images/app_logo.png",
width: 200.0,
fit: BoxFit.cover,
),
),
const Text(
"FM Mahanama is currently offline!",
style: TextStyle(fontSize: 18.0),
),
const Padding(
padding: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 20.0),
child: Text(
"Checkout our Facebook for page more information"),
),
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 20.0),
child: TextButton.icon(
onPressed: () {
_openFacebookPage();
},
icon: const Icon(Icons.link_rounded),
label: const Text("Facebook Page"),
),
),
],
),
),
visible: data.data?.get("onair"),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
elevation: 10.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(30.0),
child: Image.network(
data.data?.get("cover_img"),
width: 300.0,
height: 300.0,
fit: BoxFit.fitHeight,
),
),
),
),
const Padding(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 5.0),
child: Text(
"Now Playing",
style: TextStyle(fontSize: 22.0),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 20.0),
child: Text(
data.data!.get("nowplaying").toString(),
style: const TextStyle(
fontSize: 24.0, fontWeight: FontWeight.w600),
),
),
const Padding(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 5.0),
child: Text(
"By",
style: TextStyle(fontSize: 18.0),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
child: Text(
data.data!.get("by").toString(),
style: const TextStyle(
fontSize: 22.0, fontWeight: FontWeight.w600),
),
),
ElevatedButton.icon(
onPressed: () {
if(!assetsAudioPlayer.isPlaying.value) {
initRadioPlayer(data.data?.get("link"));
updateButtonText("Stop", Icons.stop_rounded);
}else{
assetsAudioPlayer.stop();
updateButtonText("Play", Icons.play_arrow_rounded);
}
},
label: Text(getButtonString(), style: const TextStyle(fontSize: 24.0),),
icon: Icon(iconPlayStop, size: 24.0,),
),
],
),
),
);
} else {
return const Text("There is a error loading data!");
}
},
),
),
const Center(
child: Text("Scoreboard"),
),
const Center(
child: Text("About"),
),
};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(widget.title),
),
),
body: Center(
child: _appPages.elementAt(_selectedAppIndex),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.transparent,
elevation: 0,
currentIndex: _selectedAppIndex,
selectedFontSize: 14,
unselectedFontSize: 14,
showUnselectedLabels: false,
onTap: (value) {
setState(() {
_selectedAppIndex = value;
});
},
items: const [
BottomNavigationBarItem(
label: "Player",
icon: Icon(Icons.music_note_rounded),
),
BottomNavigationBarItem(
label: "Scoreboard",
icon: Icon(Icons.scoreboard_rounded),
),
BottomNavigationBarItem(
label: "About",
icon: Icon(Icons.info_rounded),
),
],
),
);
}
static String getButtonString() {
if(assetsAudioPlayer.isPlaying.value){
return "Stop";
}else{
return "Play";
}
}
}
What I want is to update the button text and icon stop text and icon to when the button is pressed and the player is playing and vice versa.
I am using the latest build of flutter with material design widgets. I am building for android and ios.
you need to tell your code when did you change the state by doing setState()
ElevatedButton.icon(
onPressed: () {
setState(() {// add this whenever you want to change the values and update your screen
if(!assetsAudioPlayer.isPlaying.value) {
initRadioPlayer(data.data?.get("link"));
updateButtonText("Stop", Icons.stop_rounded);
}else{
assetsAudioPlayer.stop();
updateButtonText("Play", Icons.play_arrow_rounded);
}
});
},
label: Text(getButtonString(), style: const
TextStyle(fontSize: 24.0),),
icon: Icon(iconPlayStop, size: 24.0,),
),
You can use like that:
ElevatedButton.icon(
onPressed: () async {
await getButtonString();
setState(() {
});
},
label: Text(getButtonString(), style: const
TextStyle(fontSize: 24.0),),
icon: Icon(iconPlayStop, size: 24.0,),
),
For more information https://dart.dev/codelabs/async-await
I found a solution for this. It seems that setState isn't working for my app. So I implemented ValueNotifier and ValueListenableBuilder to update the values.
First I initialised the variables
ValueNotifier<IconData> iconPlayStop = ValueNotifier(Icons.play_arrow_rounded);
ValueNotifier<String> txtPlayStop = ValueNotifier("Play");
Then in button on click I updated the code to change the values on both value notifiers.
onPressed: () {
if(!assetsAudioPlayer.isPlaying.value) {
initRadioPlayer(data.data?.get("link"));
txtPlayStop.value = "Stop";
iconPlayStop.value = Icons.stop_rounded;
iconPlayStop.notifyListeners();
}else{
assetsAudioPlayer.stop();
txtPlayStop.value = "Play";
iconPlayStop.value = Icons.play_arrow_rounded;
}
},
Then on both label and icon I added ValueListenableBuilders
label: ValueListenableBuilder(
valueListenable: txtPlayStop,
builder: (BuildContext context, String value, Widget? child) => Text(value, style: const TextStyle(fontSize: 24.0),),
),
icon: ValueListenableBuilder(
valueListenable: iconPlayStop,
builder: (BuildContext context, IconData value, Widget? child) => Icon(value, size: 24.0,),
),

flutter: Edit a ListView Item

i want to edit a listview item when i click on it. I managed (with inkwell) that when I click on a listview item, the bottomsheet opens again where I also create new listview items, but I just can't edit it. I've tried everything I know (I don't know much I'm a beginner). here my codes.
--main.dart--
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import '/model/transaction.dart';
import '/widget/chart.dart';
import '/widget/new_transaction.dart';
import '/widget/transactoin_list.dart';
void main() {
// WidgetsFlutterBinding.ensureInitialized();
// SystemChrome.setPreferredOrientations(
// [
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ],
// );
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale("de"),
Locale("en"),
],
debugShowCheckedModeBanner: false,
title: "URLI",
theme: ThemeData(
primarySwatch: Colors.lightGreen,
fontFamily: "JosefinSans",
textTheme: ThemeData()
.textTheme
.copyWith(
headline4: const TextStyle(
fontFamily: "Tochter",
fontSize: 21,
),
headline5: const TextStyle(
fontFamily: "Bombing",
fontSize: 27,
letterSpacing: 3,
),
headline6: const TextStyle(
fontSize: 21,
fontWeight: FontWeight.w900,
),
)
.apply(
bodyColor: Colors.orangeAccent,
displayColor: Colors.orangeAccent.withOpacity(0.5),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
onPrimary: Colors.white,
primary: Theme.of(context).appBarTheme.backgroundColor,
textStyle: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
appBarTheme: const AppBarTheme(
titleTextStyle: TextStyle(
fontSize: 60,
fontFamily: "Tochter",
),
),
),
home: const AusgabenRechner(),
);
}
}
class AusgabenRechner extends StatefulWidget {
const AusgabenRechner({Key? key}) : super(key: key);
#override
State<AusgabenRechner> createState() => _AusgabenRechnerState();
}
class _AusgabenRechnerState extends State<AusgabenRechner> {
void _submitAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(addNewTx: _addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
bool _showChart = false;
final List<Transaction> _userTransactions = [
// Transaction(
// id: "tx1",
// tittel: "Schuhe",
// preis: 99.99,
// datum: DateTime.now(),
// ),
// Transaction(
// id: "tx2",
// tittel: "Jacke",
// preis: 39.99,
// datum: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions
.where(
(tx) => tx.datum.isAfter(
DateTime.now().subtract(
const Duration(days: 7),
),
),
)
.toList();
}
void _addNewTransaction(
String txTittel,
double txPreis,
DateTime choosenDate,
) {
final newTx = Transaction(
id: DateTime.now().toString(),
tittel: txTittel,
preis: txPreis,
datum: choosenDate,
);
setState(() {
_userTransactions.add(newTx);
});
}
void _deletedTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tdddx) => tdddx.id == id);
});
}
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final isInLandscape = mediaQuery.orientation == Orientation.landscape;
final appBar = AppBar(
centerTitle: true,
toolbarHeight: 99,
actions: [
IconButton(
onPressed: () => _submitAddNewTransaction(context),
icon: const Icon(
Icons.add,
color: Colors.white,
),
),
],
title: const Text(
"Ausgaben",
),
);
final txListWidget = SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.45,
child: TransactionList(
transaction: _userTransactions,
delettx: _deletedTransaction,
showNewTransaction: _submitAddNewTransaction,
),
);
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
children: [
if (isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.2,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Chart anzeigen",
style: Theme.of(context).textTheme.headline5,
),
const SizedBox(width: 9),
Switch.adaptive(
inactiveTrackColor:
Theme.of(context).primaryColor.withOpacity(0.3),
activeColor: Theme.of(context).primaryColor,
value: _showChart,
onChanged: (val) {
setState(() {
_showChart = val;
});
},
),
],
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.24,
child: Chart(
recentTransactions: _recentTransactions,
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.65,
child: txListWidget),
if (isInLandscape)
_showChart
? SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.51,
child: Chart(
recentTransactions: _recentTransactions,
),
)
: SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.81,
child: txListWidget)
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(
Icons.add,
color: Colors.white,
),
onPressed: () => _submitAddNewTransaction(context),
),
);
}
}
--transaction_list.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '/model/transaction.dart';
class TransactionList extends StatefulWidget {
const TransactionList({
Key? key,
required this.transaction,
required this.delettx,
required this.showNewTransaction,
}) : super(key: key);
final List<Transaction> transaction;
final Function delettx;
final Function showNewTransaction;
#override
State<TransactionList> createState() => _TransactionListState();
}
class _TransactionListState extends State<TransactionList> {
#override
Widget build(BuildContext context) {
return widget.transaction.isEmpty
? LayoutBuilder(
builder: (ctx, contrains) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Keine Daten vorhanden!",
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(
height: 30,
),
SizedBox(
height: contrains.maxHeight * 0.45,
child: Image.asset(
"assets/images/schlafen.png",
fit: BoxFit.cover,
),
)
],
);
},
)
: Align(
alignment: Alignment.topCenter,
child: ListView.builder(
shrinkWrap: true,
reverse: true,
itemCount: widget.transaction.length,
itemBuilder: (ctx, index) {
return InkWell(
onLongPress: () => widget.showNewTransaction(ctx),
child: Card(
elevation: 5,
child: ListTile(
leading: CircleAvatar(
radius: 33,
child: Padding(
padding: const EdgeInsets.all(9.0),
child: FittedBox(
child: Row(
children: [
Text(
widget.transaction[index].preis
.toStringAsFixed(2),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24,
),
),
const Text(
"€",
style: TextStyle(
fontSize: 21,
),
)
],
),
),
),
),
title: Text(
widget.transaction[index].tittel,
style: Theme.of(context).textTheme.headline6,
),
subtitle: Text(
DateFormat.yMMMMd("de")
.format(widget.transaction[index].datum),
style: Theme.of(context).textTheme.headline4,
),
trailing: MediaQuery.of(context).size.width > 460
? TextButton.icon(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
),
label: const Text("Löschen"),
style: TextButton.styleFrom(
primary: Colors.red,
),
)
: IconButton(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
color: Colors.red,
),
),
),
),
);
},
),
);
}
}
--new_transaction.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
const NewTransaction({Key? key, required this.addNewTx}) : super(key: key);
final Function addNewTx;
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _tittelcontroller = TextEditingController();
final _preiscontroller = TextEditingController();
DateTime? _selectedDate;
void _submitData() {
final enteredTittel = _tittelcontroller.text;
final enteredPreis = double.parse(_preiscontroller.text);
if (_preiscontroller.text.isEmpty) {
return;
}
if (enteredTittel.isEmpty || enteredPreis <= 0 || _selectedDate == null) {
return;
}
widget.addNewTx(
_tittelcontroller.text,
double.parse(_preiscontroller.text),
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2022),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
bottom: false,
child: SingleChildScrollView(
child: Container(
//height: MediaQuery.of(context).size.height * 0.5,
padding: EdgeInsets.only(
top: 10,
left: 18,
right: 18,
bottom: MediaQuery.of(context).viewInsets.bottom + 10,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextButton(
onPressed: _submitData,
child: Text(
"hinzufügen",
style: Theme.of(context).textTheme.headlineSmall,
),
),
TextField(
controller: _tittelcontroller,
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Tittel"),
),
),
TextField(
controller: _preiscontroller,
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Preis"),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 66),
child: Center(
child: Column(
children: [
Text(
_selectedDate == null
? "Kein Datum ausgewählt"
: DateFormat.yMMMMEEEEd("de")
.format(_selectedDate!),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(
height: 21,
),
ElevatedButton(
style: Theme.of(context).elevatedButtonTheme.style,
onPressed: _presentDatePicker,
child: const Text("Datum wählen"),
),
],
),
),
)
],
),
),
),
);
}
}
EN: Here is an excample code, how i would solve this, when i understood the problem. The passing of the variables to the new Class is a bit differnent then in your Code but it works the same.
DE: So hier ist jetzt ein Beispielcode, wie ich es lösen würde, wenn ich das Problem richtig verstanden habe, dabei werden die Variabeln etwas anders als bei dir in die neue Klasse übergeben, funktioniert aber gleich
class testListview extends StatefulWidget {
var transaction;
var delettx;
var showNewTransaction;
//Passing the data to new Class
testListview(this.transaction, this.delettx,
this.showNewTransaction);
#override
State<testListview> createState() => _testListviewState();
}
class _testListviewState extends State<testListview> {
var transaction;
var delettx;
var showNewTransaction;
//Pass the data into the State of the new Class
_testListviewState(this.transaction, this.delettx,
this.showNewTransaction);
var transaction_2;
//The init state will be called in the first initialization of
//the Class
#override
void initState() {
//Pass your transactions to a new variable
setState(() {
transaction_2 = transaction;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (BuildContext context,
index){
return TextButton(onPressed: (){
//Change the data with onPressed
setState(() {
transaction_2["preis"] = "500";
});
}, child: Text(transaction_2["preis"]));
});}}

The instance member 'posts' can't be accessed in an initializer

I would like to load other REST CALL which callS other data from DB.
I would like to use bottom navigation bar.
When I coded without bottom navigation bar, the app worked.
But When I inserted bottom navigation bar, "posts" function(related to REST CALL) has an error.
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (context, index) {
Post post = posts[index];
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'Services.dart';
import 'Post.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter ListView'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<Post> posts;
late bool loading;
#override
void initState() {
super.initState();
loading = true;
Services.getPosts().then((list) {
super.setState(() {
posts = list;
loading = false;
});
});
}
#override
int _selectedIndex = 0;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(loading ? 'Loading...' : 'Posts'),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.grey,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white.withOpacity(.60),
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _selectedIndex,
//현재 선택된 Index
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
},
items: [
BottomNavigationBarItem(
title: Text('Favorites'),
icon: Icon(Icons.favorite),
),
BottomNavigationBarItem(
title: Text('Music'),
icon: Icon(Icons.music_note),
),
BottomNavigationBarItem(
title: Text('Places'),
icon: Icon(Icons.location_on),
),
BottomNavigationBarItem(
title: Text('News'),
icon: Icon(Icons.library_books),
),
],
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
);
}
List _widgetOptions = [
Column(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// crossAxisAlignment:CrossAxisAlignment.center,
children: [
Container(
color: Colors.amber,
child: Row(
children: const [
Expanded(
child: Center(
child: Text('Date',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('Koreanwon/us\$',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('Koreanwon',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('US \$',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
],
),
),
Expanded(
child: Center(
child: Container(
child: ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (context, index) {
Post post = posts[index];
return Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.blueAccent)),
),
child: ListTile(
title: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child: Center(child: Text(post.date))),
Expanded(child: Center(child: Text(post.rate))),
Expanded(
child: Center(child: Text(post.koreanwon))),
Expanded(child: Center(child: Text(post.dollar))),
],
),
),
// ),
);
}),
),
),
),
],
),
];
}
You're trying to access an instance variable (posts), in another instance variable(_widgetOptions). This is disallowed as you're trying to access something that isn't. Move the initialization into the initState.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'Services.dart';
import 'Post.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter ListView'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<Post> posts;
late bool loading;
late List _widgetOptions;
#override
void initState() {
super.initState();
loading = true;
Services.getPosts().then((list) {
super.setState(() {
posts = list;
loading = false;
});
});
//You have to initialize _widgetOptions into the `initState` method.
_widgetOptions = [
Column(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// crossAxisAlignment:CrossAxisAlignment.center,
children: [
Container(
color: Colors.amber,
child: Row(
children: const [
Expanded(
child: Center(
child: Text('Date',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('Koreanwon/us\$',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('Koreanwon',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
Expanded(
child: Center(
child: Text('US \$',
style: TextStyle(
height: 2.5,
fontSize: 18,
fontWeight: FontWeight.bold,
leadingDistribution: TextLeadingDistribution.even,
)))),
],
),
),
Expanded(
child: Center(
child: Container(
child: ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (context, index) {
Post post = posts[index];
return Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.blueAccent)),
),
child: ListTile(
title: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child: Center(child: Text(post.date))),
Expanded(child: Center(child: Text(post.rate))),
Expanded(
child: Center(child: Text(post.koreanwon))),
Expanded(child: Center(child: Text(post.dollar))),
],
),
),
// ),
);
}),
),
),
),
],
),
];
}
#override
int _selectedIndex = 0;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(loading ? 'Loading...' : 'Posts'),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.grey,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white.withOpacity(.60),
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _selectedIndex,
//현재 선택된 Index
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
},
items: [
BottomNavigationBarItem(
title: Text('Favorites'),
icon: Icon(Icons.favorite),
),
BottomNavigationBarItem(
title: Text('Music'),
icon: Icon(Icons.music_note),
),
BottomNavigationBarItem(
title: Text('Places'),
icon: Icon(Icons.location_on),
),
BottomNavigationBarItem(
title: Text('News'),
icon: Icon(Icons.library_books),
),
],
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
);
}
}

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