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

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),
),
);
}
}

Related

Problem in multilingualizing the app in 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'),
),
],
),
),
),
);
}
}

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

what is the best way to implement this home screen?

I would like to create a home page for my flutter app. I used templates from the network, but unfortunately I don't get it the way I sketched it in the picture. maybe someone can help me with that
sketch / result
Unfortunately, I'm sure that I can't do it better: - /, would like to have it exactly like the one on the left (icons and colors are not so important)
I used this link from the forum as a template for the appbar, and I had difficulties in inserting it ^^
Custom AppBar Flutter
I also got the code for the BottomNavigationBar from somewhere in the forum, but I think this is not suitable for my purposes anyway. Since I don't like this shrink effect when clicking on it, the two arrow buttons at the edge should snap back when pressed and not stay in the pressed state, as they should stand for the front and back function ...
here is my complete main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
Color _getBgColor(int index) =>
_selectedIndex == index ? _selectedBgColor : _unselectedBgColor;
Color _getItemColor(int index) =>
_selectedIndex == index ? _selectedItemColor : _unselectedItemColor;
Widget _buildIcon(IconData iconData, String text, int index) => Container(
width: double.infinity,
height: kBottomNavigationBarHeight,
child: Material(
color: _getBgColor(index),
child: InkWell(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(iconData),
Text(text,
style: TextStyle(fontSize: 9, color: _getItemColor(index))),
],
),
onTap: () => _onItemTapped(index),
),
),
);
_appBar(height) => PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, height+80 ),
child: Stack(
children: <Widget>[
Container(
child: Center(
child: Text("TEXT", style: TextStyle(fontSize: 15.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
color:Theme.of(context).primaryColor,
height: height+75,
width: MediaQuery.of(context).size.width,
),
Container(
),
Positioned( // To take AppBar Size only
top: 100.0,
left: 20.0,
right: 20.0,
child: AppBar(
backgroundColor: Color(0xFF293749),
leading: Icon(Icons.menu, color: Colors.white),
primary: false,
title: Container(
margin: EdgeInsets.only(top: 4.0, bottom: 4.0, right: 0.0, left: 0.0),
color: Colors.white,
child: Container(
margin: EdgeInsets.only(top: 0.0, bottom: 0.0, right: 5.0, left: 5.0),
child: TextField(
decoration: InputDecoration(
hintText: "Suchen",
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey))),
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.white), onPressed: () {},),
],
),
)
],
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(AppBar().preferredSize.height),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_back_ios_rounded, 'ZURÜCK', 0),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.favorite, 'FAVORITEN', 1),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.comment, 'KOMMENTARE', 2),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.info_outline_rounded, 'ÜBER UNS', 3),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_forward_ios_rounded, 'WEITER', 4),
title: SizedBox.shrink(),
),
],
currentIndex: _selectedIndex,
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
),
);
}
}
I have modified your code with some commentaries to support you in building the UI.
For the AppBar, you are going in the right direction of using PreferredSize with Stack, just some minor adjustments.
For the BottomNavigationBar, since the provided BottomNavigationBarItem has the icon and title attributes already, we can use that and modify the color from their parents. The 2 arrows buttons can be placed together within the Row.
Here's the full example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
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> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
_appBar() => PreferredSize(
preferredSize: Size.fromHeight(300),
child: Container(
height: 300,
child: Stack(
children: <Widget>[
Container(
color: Color(0xFF34445D),
height: 180,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"APP TITLE",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(
4,
(index) => Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Icon(Icons.people, color: Colors.white), // Sample icons for demonstration
),
),
)
],
),
),
Positioned(
top: 150.0,
left: 20.0,
right: 20.0,
child: Container(
color: Color(0xFF293749),
child: Row(
children: [
IconButton(
icon: Icon(Icons.menu, size: 40, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(vertical: 3),
padding: EdgeInsets.only(left: 3),
color: Colors.white,
height: 30,
child: TextField(
style: TextStyle(color: Colors.black, fontSize: 12),
decoration: InputDecoration(
hintText: 'Search...',
border: InputBorder.none),
),
),
),
IconButton(
icon: Icon(Icons.search, size: 30, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
],
),
),
),
],
),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: Container(
color: _selectedBgColor,
child: Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex <= 0 ? _selectedIndex : _selectedIndex - 1;
});
},
),
Expanded(
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed, // Add the type here to avoid auto resize
backgroundColor: _selectedBgColor, // You can also set the unselectedBackgroundColor
currentIndex: _selectedIndex,
onTap: (index) => setState(() => _selectedIndex = index), // Update the selected index
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.favorite), title: Text('FAVORITEN')),
BottomNavigationBarItem(
icon: Icon(Icons.comment), title: Text('KOMMENTARE')),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline_rounded),
title: Text('ÜBER UNS')),
],
),
),
IconButton(
icon: Icon(Icons.arrow_forward_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex >= 2 ? _selectedIndex : _selectedIndex + 1;
});
},
),
],
),
),
);
}
}

How to use itemBuilder to select the last tapped ListTile widget?

I am trying to change the selected property of the last tapped ListTile widget to true inside a Drawer (and then obviously the selected property of other ListTiles to false), but I do not understand how can I use itemBuilder (which is mentioned in the official flutter docs) for this.
I tried putting my ListTiles into an AnimatedListItemBuilder widget, but that was not working for me.
Widget _buildDrawer() {
return ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child:
Wrap(
alignment: WrapAlignment.center,
direction: Axis.vertical,
children: <Widget>[
Text(
_currentUser.displayName,
style: TextStyle(
fontSize: 20,
color: Colors.white
),
),
Wrap(
direction: Axis.vertical,
children: <Widget>[
Text(
"Iskolai kategória: A",
style: TextStyle(
fontSize: 18,
color: Colors.white70
),
),
Text(
"Kollégiumi kategória: A",
style: TextStyle(
fontSize: 18,
color: Colors.white70
),
),
],
)
],
),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
selected: true,
leading: Icon(Icons.date_range_rounded),
title: Text('Stúdium jelentkezés'),
onTap: () {
// Update the state of the app.
// ...
// Then close the drawer.
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.article_rounded),
title: Text('Koleszhírek'),
onTap: () {
// Update the state of the app.
// ...
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.account_box_rounded),
title: Text('Profil'),
onTap: () {
// Update the state of the app.
// ...
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.logout),
title: Text('Kijelentkezés'),
onTap: () => {
_googleSignIn.disconnect(),
Navigator.pop(context)
},
),
],
);
}
You have to save the 'selected index' in a variable and check if the current index equals selected index to highlight the ListView. I've updated your code to make it work.
import 'package:flutter/material.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 Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
drawer: _buildDrawer(context),
body: Center(
child: Text("DrawerHeader Demo"),
),
);
}
Widget _buildDrawer(BuildContext context) {
List<Widget> leading = [
Icon(Icons.date_range_rounded),
Icon(Icons.article_rounded),
Icon(Icons.account_box_rounded),
Icon(Icons.logout),
];
List<Widget> title = [
Text('Stúdium jelentkezés'),
Text('Koleszhírek'),
Text('Profil'),
Text('Kijelentkezés'),
];
return Container(
color: Colors.white,
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Wrap(
alignment: WrapAlignment.center,
direction: Axis.vertical,
children: <Widget>[
Text(
"A",
style: TextStyle(fontSize: 20, color: Colors.white),
),
Wrap(
direction: Axis.vertical,
children: <Widget>[
Text(
"Iskolai kategória: A",
style: TextStyle(fontSize: 18, color: Colors.white70),
),
Text(
"Kollégiumi kategória: A",
style: TextStyle(fontSize: 18, color: Colors.white70),
),
],
)
],
),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListView.builder(
itemCount: 4,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: title[index],
leading: leading[index],
selected: index == _selectedIndex,
onTap: () {
setState(() {
_selectedIndex = index;
Navigator.pop(context);
});
},
);
},
),
],
),
);
}
}

How to use implement calendar in flutter

I'm new to flutter and struggling to follow the use of external packages. An example is implementing the calendar from https://flutterawesome.com/flutter-rounded-date-picker
My code is shown below:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'), // English
],
title: 'Calendar Tester',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Timesheet"),
backgroundColor: Colors.blueGrey[900],
centerTitle: true,
),
body: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
Container(
child: Text('JX',
style: TextStyle(color: Colors.white),),
margin: EdgeInsets.fromLTRB(15,15,15,5),
padding:EdgeInsets.all(10),
decoration: BoxDecoration(
shape:BoxShape.circle,
color: Colors.black,
),
),
Text('John X',
style: TextStyle(color: Colors.black),
),
],
),
Column(
children: [
Container(
margin:EdgeInsets.fromLTRB(70,25,15,5) ,
child: Text("MONDAY, 11 JULY 2020",
style: TextStyle(color: Colors.blue),
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 16.0),
// child:
)
],
)
],
),
);
}
}
I simply want to include the calendar in the last container, using the child property that I have currently commented out. The docs for the library say I should just do this:
DateTime newDateTime = await showRoundedDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year - 1),
lastDate: DateTime(DateTime.now().year + 1),
borderRadius: 16,
),
Where exactly does this go and how do I get to show the calendar? Only interested in getting the calendar to show at the moment.
class MyHomePage extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
DateTime dateTime;
Duration duration;
#override
void initState() {
dateTime = DateTime.now();
duration = Duration(minutes: 10);
super.initState();
}
#override
Widget build(BuildContext context) {
Widget _buildBody() {
return Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(16),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
"Date Time selected",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
color: Colors.grey[600],
),
),
Text(
"$dateTime",
style: const TextStyle(fontSize: 20),
),
Text(
"Duration Selected",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, color: Colors.grey[600]),
),
Text(
"$duration",
style: const TextStyle(fontSize: 20),
),
],
),
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.only(bottom: 50),
children: <Widget>[
const SizedBox(height: 16),
FloatingActionButton.extended(
onPressed: () async {
DateTime newDateTime = await showRoundedDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year - 1),
lastDate: DateTime(DateTime.now().year + 1),
borderRadius: 2,
);
if (newDateTime != null) {
setState(() => dateTime = newDateTime);
}
},
label: const Text("Material Calendar (Original)"),
),
],
),
),
],
);
}
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Rounded Date Picker'),
),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 32),
child: _buildBody(),
),
);
}
}