I'm using firebase to send notifications to my app what happens is that I reserved the notifications in the terminal but it's not shown in my application
so how can I handle the notification in a widget so it appears inside the application
I'm trying to set state the text message variable so that its value become the notification body instead of null but its not working
my code is that
[import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:idb/pages/aboutus.dart';
import 'package:idb/pages/adminpage.dart';
import 'package:idb/pages/changePassword.dart';
import 'package:idb/pages/homepage.dart';
import 'package:idb/pages/logout.dart';
import 'package:idb/pages/newsPage.dart';
import 'dart:io';
class NotificationsPage extends StatefulWidget {
_NotificationsPageState createState() => _NotificationsPageState();
}
class _NotificationsPageState extends State<NotificationsPage> {
final FirebaseMessaging _messaging = new FirebaseMessaging();
//String testMessage;
Map<String, dynamic> testMessage;
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_messaging.getToken().then((token) {
print('notification token $token');
});
_messaging.configure(
onMessage: (Map<String, dynamic> message) async {
// print('message ${message}');
setState(() {
testMessage = message\['notification'\]\['body'\];
print('testMessage ${testMessage}');
});
},
onResume: (Map<String, dynamic> message) async {
// print('message ${message}');
//print('on resume ${message\['notification'\]\['body'\]}');
setState(() {
String testMessage = message\['notification'\]\['body'\];
print('testMessage onResume ${testMessage}');
});
},
onLaunch: (Map<String, dynamic> message) async {
// print('message ${message}');
// print('on launch $message');
setState(() {
String testMessage = message\['notification'\]\['body'\];
print('testMessage onLaunch ${testMessage}');
});
},
);
}
void iOS_Permission() {
_messaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_messaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
int _cIndex = 1;
void _incrementTab(index) {
setState(() {
_cIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: new Drawer(
child: new ListView(children: <Widget>\[
new Container(
child: new DrawerHeader(
child: Image.asset('assets/t.jpg'),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => AdminPage()),
);
},
),
ListTile(
leading: Icon(Icons.credit_card),
title: Text('My Cards'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => HomePage()),
);
},
),
ListTile(
leading: Icon(Icons.message),
title: Text('News'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => NewsPage()),
);
},
),
ListTile(
leading: Icon(Icons.info),
title: Text('About Us'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => AboutUs()),
);
},
),
Divider(),
ListTile(
leading: Icon(Icons.lock_outline),
title: Text('Change Password'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => ChangePassword()),
);
},
),
Logout(),
\]),
),
appBar: AppBar(
title: Text(
'Notifications',
style: TextStyle(color: Colors.blueGrey),
),
backgroundColor: Colors.grey\[100\],
centerTitle: true,
elevation: 0.0,
),
body: Center(
child: Container(
child: Text(
'$testMessage',
style:
new TextStyle(color: Colors.grey, fontWeight: FontWeight.w400),
),
),
),
bottomNavigationBar: BottomNavigationBar(
fixedColor: Colors.orange,
currentIndex: _cIndex,
//fixedColor: Colors.grey\[100\],
type: BottomNavigationBarType.shifting,
items: \[
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: Colors.blueGrey,
),
title: Text('Home',
style: TextStyle(
color: Colors.blueGrey,
)),
),
BottomNavigationBarItem(
icon: Icon(
Icons.notifications,
color: Colors.blueGrey,
),
title: Text('Notifications',
style: TextStyle(
color: Colors.blueGrey,
)),
),
BottomNavigationBarItem(
icon: Icon(
Icons.message,
color: Colors.blueGrey,
),
title: Text('News',
style: TextStyle(
color: Colors.blueGrey,
)),
),
\],
onTap: (index) {
if (index == 0) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => AdminPage()),
);
}
if (index == 1) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => NotificationsPage()),
);
}
if (index == 2) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => NewsPage()),
);
}
_incrementTab(index);
// _incrementTab(index);
},
),
);
}
#override
void initState() {
super.initState();
firebaseCloudMessaging_Listeners();
}
}
]1]1
Related
I am building an application where I need to use Flutter maps, everything work as expected, however if I make a build through Jankins for release mode then for some reason the maps on iOS displays blank. I have another page where the same widget is opened in a full page and there it works. My thoughts are that placing google maps in SingleChildScrolView causes the issue. Below I am attaching the source code.I have replaced the SingleChildScrolView with with list view where I pass all widgets as children but the effect is the same, the map is displayed in debug mode but when building through Jankins the map is blank , but on another page the map widget is working as expected.
Any help will be greatly appreciated as I am banging my head for hours.
Regards
class DashboardPage extends StatefulWidget {
final Model _model;
DashboardPage(this._model);
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
List<Dossier> _dossiers = List();
_DashboardPageState();
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(shrinkWrap: true, children: <Widget>[
_header(StringResources.dashboardTitle),
_mapWidget(),
_header(StringResources.myFiles),
_listWidgets()
],),
);
}
Widget _mapWidget() {
return Container(
height: 300,
child: DossierMap(
compassEnabled: false,
model: widget._model,
onDossierMapViewCreated: _onMapWidgetCreated,
onDossierInfoWindowTap: _selectedMarker,
),
);
}
Widget _listWidgets() {
return StreamBuilder<List<Dossier>>(
initialData: [],
stream: widget._model.dossierService
.loadDossiers(widget._model.loginService.token)
.catchError((e) {
if (widget._model.loggedIn) {
widget._model.forcedServerLogout();
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) {
return LoginPage(
model: widget._model,
errorText: "",
onLoggedInCallback: (context) => Navigator.of(context)
.pushReplacement(MaterialPageRoute(
builder: (context) => DossiersPage(widget._model))),
);
},
));
}
}).asStream(),
builder: (_context, snapshot) {
if (snapshot.hasData) {
_dossiers = snapshot.data;
return snapshot.data.length != 0
? _buildList(snapshot.data)
: _noDossierContentWidget();
} else if (snapshot.hasError) {
return _progressIndicator();
} else {
return _progressIndicator();
}
});
}
Widget _header(String text) {
return new Container(
decoration: new BoxDecoration(color: Color(ColorResources.darkGray)),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 0, 12),
child: Align(
alignment: Alignment.centerLeft,
child: Text(text,
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontWeight: FontWeight.w500,
fontSize: 17,
color: Colors.white))),
),
);
}
void _onMapWidgetCreated(dynamic controller) {
controller.setMarkers(_dossiers);
}
Widget _buildList(List<Dossier> dossierList) {
return Container(
color: Color(ColorResources.dividerColor),
height: 400,
child: ListView.separated(
padding: EdgeInsets.all(0.0),
separatorBuilder: (context, index) =>
Divider(color: Colors.grey.shade300, height: 1.5),
itemCount: dossierList != null ? dossierList.length : 0,
shrinkWrap: true,
physics: ScrollPhysics(),
itemBuilder: (BuildContext context, int index) => DossierListItem(
dossier: dossierList[index],
fromSearch: true,
widget: Icon(
Icons.keyboard_arrow_right,
size: 30,
color: Color(ColorResources.gray),
),
onListItemClickListener: () =>
onListItemClicked(dossierList[index]),
)));
}
void onListItemClicked(Dossier dossier) {
_selectedDossier(dossier);
}
Widget _progressIndicator() {
return Center(child: CircularProgressIndicator());
}
Widget _noDossierContentWidget() {
return Container(
color: Theme.of(context).cardColor,
child: ListTile(
title: Text(
StringResources.noOwnedFiles,
softWrap: true,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).primaryTextTheme.caption,
),
));
}
void _selectedMarker(DossierCluster cluster) async {
if (cluster.isCluster) {
Dossier selected = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
contentPadding: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 24.0),
title: Center(child: Text(StringResources.selectFile)),
content: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
children:
dossiersFromCluster(cluster, onDossierListMarkerClick),
),
),
actions: <Widget>[
FlatButton(
child: Text(StringResources.cancel),
onPressed: () => Navigator.pop(context),
)
],
);
});
if (selected != null) _selectedDossier(selected);
} else {
_selectedDossier(cluster.getFirst);
}
}
List<Widget> dossiersFromCluster(
DossierCluster cluster, Function onDossierListMarkerClick) {
List<Widget> widgets = List();
for (int i = 0; i < cluster.size; i++) {
Dossier dossier = cluster.get(i);
widgets.add(DossierListItem(
dossier: dossier,
fromSearch: false,
widget: Container(),
onListItemClickListener: () => onDossierListMarkerClick(dossier),
));
}
return widgets;
}
void _selectedDossier(Dossier dossier) {
widget._model.setDossier(dossier);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DossierDetailsPage(widget._model)),
);
}
void _openFullSize() {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => FullScreenMapPage(widget._model, _dossiers),
),
);
}
void onDossierListMarkerClick(Dossier dossier) {
widget._model.setDossier(dossier);
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => DossierDetailsPage(widget._model)));
}
}
I want to show a AlertDialog whenever I Tap on the ListTile. I want to add the AlertDialog in the OnTap functon in the ListTile as shown in the code.
import "package:flutter/material.dart";
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Exploring Ui Widgets',
home: Scaffold(
body: getListView(),
),
));
}
Widget getListView() {
var listview = ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.accessible),
title: Text('Get Up!'),
subtitle: Text('Use your Legs!'),
trailing: Icon(Icons.accessible_forward),
onTap: () {
// I want to add a AlertDialog here!
},
),
ListTile(
leading: Icon(Icons.airline_seat_individual_suite),
title: Text('Wake Up!'),
subtitle: Text('Dont Sleep!'),
trailing: Icon(Icons.airline_seat_flat_angled),
)
],
);
return listview;
}
You can do it like this:
onTap: () => alertDialog(context),
Then declare this method:
void alertDialog(BuildContext context) {
var alert = AlertDialog(
title: Text("My title"),
content: Text("Dialog description"),
);
showDialog(context: context, builder: (BuildContext context) => alert);
}
It would look like this inside your code:
import "package:flutter/material.dart";
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Exploring Ui Widgets',
home: Scaffold(
body: getListView(),
),
));
}
Widget getListView() {
var listview = ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.accessible),
title: Text('Get Up!'),
subtitle: Text('Use your Legs!'),
trailing: Icon(Icons.accessible_forward),
onTap: () {
onTap: () => alertDialog(context),
},
),
ListTile(
leading: Icon(Icons.airline_seat_individual_suite),
title: Text('Wake Up!'),
subtitle: Text('Dont Sleep!'),
trailing: Icon(Icons.airline_seat_flat_angled),
)
],
);
return listview;
}
void alertDialog(BuildContext context) {
var alert = AlertDialog(
title: Text("Dialog title"),
content: Text("Dialog description"),
);
showDialog(context: context, builder: (BuildContext context) => alert);
}
I was using some shared preferences to read and save lists but all I got is an error that goes as follows:
Launching lib/main.dart on iPhone 7 in debug mode...
Xcode build done. 4.1s
Tried calling: getString("t")
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 ShareUtils.get
package:todolist2019/ShareUtils.dart:22
<asynchronous suspension>
#2 HomeScreenState.getTaskTitle
package:todolist2019/home.dart:38
#3 _AsyncAwaitCompleter.start (dart:async/runtime/libasync_patch.dart:49:6)
#4 HomeScreenState.getTaskTitle
package:todolist2019/home.dart:35
#5 HomeScreenState.build.<anonymous closure>
package:todolist2019/home.dart:97
#6 SliverChildBuilderDelegate.build
package:flutter/…/widgets/sliver.dart:398
Here is my code for home.dart, my home screen
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import './additem.dart';
import './ShareUtils.dart';
class HomeScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return HomeScreenState();
}
}
Timer timer;
DateTime now = DateTime.now();
String formattedTime = DateFormat('kk:mm').format(now);
String formattedDate = DateFormat('EEE d MMM').format(now);
class HomeScreenState extends State<HomeScreen> {
void changeTimeAndSetPref() {
setState(() {
DateTime now = DateTime.now();
formattedTime = DateFormat('kk:mm').format(now);
formattedDate = DateFormat('EEE d MMM').format(now);
});
}
Future getTaskTitle(index) async {
shareUtils = new ShareUtils();
shareUtils.Instance();
await shareUtils.get("title"[index]);
}
void initState() {
super.initState();
// Add listeners to this class
timer = Timer.periodic(Duration(seconds: 1), (Timer t) => changeTimeAndSetPref());
}
#override
Widget build(BuildContext context) {
// TODO: implement build
SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => addItem()),
);
},
icon: Icon(Icons.add),
label: Text("Add Item"),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: Column(
children: <Widget>[
Center(
//set the correct sizes
child: Card(
child: Column(
children: <Widget>[
Text(
formattedTime,
style: TextStyle(
fontSize: 50.0,
),
),
Text(
formattedDate,
style: TextStyle(
fontSize: 35.0,
),
),
Text(
"You have impending tasks",
style: TextStyle(
fontSize: 25.0,
),
)
],
),
),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
var title = getTaskTitle(index).toString();
var detail = taskTitleList[index];
EdgeInsets.all(16.0);
return ListTile(
title: Text(
title,
style: TextStyle(fontSize: 20.0),
),
subtitle: Text(
detail,
style: TextStyle(fontSize: 15.0),
),
onTap: () {
final snackBar = SnackBar(
content: Text('Item Removed'),
duration: Duration(seconds: 1),
);
setState(() {
taskTextList.removeAt(index);
taskTitleList.removeAt(index);
Scaffold.of(context).showSnackBar(snackBar);
});
},
);
},
itemCount: taskTextList.length,
),
)
],
),
);
}
}
And here is my code for additem.dart
import 'package:flutter/material.dart';
import './home.dart';
import './ShareUtils.dart';
class addItem extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return addItemState();
}
}
ShareUtils shareUtils;
var TaskTextField;
var TaskDetailField;
var taskTextList = [];
var taskTitleList = [];
var TaskIsImportant = false;
class addItemState extends State<addItem> {
#override
Widget build(BuildContext context) {
// TODO: implement build
void saveTask (key, value) async {
await shareUtils.set(key, value);
}
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
setState(()async {
if (TaskIsImportant) {
taskTextList.add("❗$TaskTextField");
taskTitleList.add("$TaskDetailField");
saveTask("title", taskTextList);
} else {
taskTextList.add("$TaskTextField");
taskTitleList.add("$TaskDetailField");
saveTask("title", taskTextList);
}
});
},
label: Text("Add Task"),
icon: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: Flex(
direction: Axis.vertical,
children: <Widget>[
Flexible(
child: Container(
child: Column(
children: <Widget>[
Card(
child: Column(
children: <Widget>[
Center(
child: Text(
"Welcome!",
style: TextStyle(fontSize: 50.0),
),
),
Center(
child: Text(
"Enter your task below",
style: TextStyle(fontSize: 25.0),
),
),
],
),
),
Container(
child: TextField(
decoration: InputDecoration(
hintText: "Enter title of task to be added",
hintStyle: TextStyle(fontSize: 20.0)),
onChanged: (taskTextField) {
setState(() {
TaskTextField = taskTextField;
print(TaskTextField);
});
},
),
margin: EdgeInsets.all(16.0),
),
Container(
child: TextField(
decoration: InputDecoration(
hintText: "Enter detail of task to be added",
hintStyle: TextStyle(fontSize: 20.0)),
onChanged: (taskDetailField) {
setState(() {
TaskDetailField = taskDetailField;
print(TaskDetailField);
});
},
),
margin: EdgeInsets.all(16.0),
),
CheckboxListTile(
title: Text(
"Important",
style: TextStyle(fontSize: 25.0),
),
activeColor: Colors.blue,
value: TaskIsImportant,
onChanged: (val) {
setState(() {
TaskIsImportant = !TaskIsImportant;
print(TaskIsImportant);
});
},
),
],
),
),
)
],
));
}
}
I hope someone can help me with this error. I am running on Flutter 1.2.1. Thanks in advance!
PS: I have implemented the Akio's code and I still got errors but lesser. I have also added the first 6 lines of error message.
You can add "shared_preferences: ^0.4.0" at pubspec.yaml.
And Packages get.
And you make DartFile (Ex: Filename is ShareUtils
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
class ShareUtils {
static ShareUtils _instance;
SharedPreferences ShareSave;
factory ShareUtils() => _instance ?? new ShareUtils._();
ShareUtils._();
void Instatce() async{
ShareSave = await SharedPreferences.getInstance();
}
Future<bool> set(key, value) async{
return ShareSave.setString(key, value);
}
Future<String> get(key) async{
return ShareSave.getString(key);
}
}
And main.dart
class MyApp extends StatelessWidget {
static ShareUtils shareUtils;
#override
Widget build(BuildContext context) {
ThemeData mainTheme = new ThemeData(
primaryColor : Color.fromRGBO(20, 42, 59, 1),
buttonColor: Color.fromRGBO(0, 132, 255, 1),
accentColor: Color.fromRGBO(31, 60, 83, 1)
);
shareUtils = new ShareUtils();
shareUtils.Instatce();
MaterialApp mainApp = new MaterialApp(
title: "Your app name",
theme: mainTheme,
home: new SplashPage(),
debugShowCheckedModeBanner: true,
routes: <String, WidgetBuilder>{
"HomePage": (BuildContext context) => new HomePage(),
},
);
return mainApp;
}
}
And you can Use this at anywhere
Before to use this, add import main.dart at header
GET:
Future NextPage() async {
MyApp.shareUtils.get("token").then((token) {
print(token);
if (token == null || token == "") {
Navigator.of(context).popAndPushNamed("RegisterPage");
} else {
Navigator.of(context).popAndPushNamed("HomePage");
}
});
}
SET:
void UserInfo(code, token) async{
await MyApp.shareUtils.set("token", token);
await MyApp.shareUtils.set("code", code);
await Navigator.of(context).pushNamed("HomePage");
}
I hope help you. Thank you
In your case MyApp.shareUtils.set("state", statelist.join("#"))
And get use statelist = token.split("#");
I have a problem regarding if statement in dart, I want the user to tap the city to go to a new screen. this code work perfectly fine
class citySec extends StatelessWidget {
Widget getListView(BuildContext context) {
var listView = ListView(
children: <Widget>[
Text(
"choose ur city:",
textDirection: TextDirection.rtl,
textAlign: TextAlign.center,
),
ListTile(
leading: Icon(Icons.location_city),
title: Text("Toronto ", textDirection: TextDirection.rtl),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TorontoUniversitySection(),
),
);
},
),
],
);
return listView;
}
#override
Widget build(BuildContext context) {
return Scaffold(body: getListView(context));
}
}
Since I have a long list of cities and the previous code will make my code very long so I had to change my code. However, I faced some errors with if statements, here is what I did so far.
import 'package:flutter/material.dart';
import 'package:rate/screens/firstScreen.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Rate',
home: Scaffold(
appBar: AppBar(
title: Text("jgfnjfnj ", textDirection: TextDirection.rtl),
),
body: ListDisplay(),
),
));
}
class ListDisplay extends StatelessWidget {
List<String> litems = ["Toronto","NewYork","London","Riyadh","Dubai","Istanbul"];
#override
Widget build (BuildContext ctxt) {
return new Scaffold(
appBar: AppBar(title: Text("Please Choose your city: ", textDirection: TextDirection.ltr,),
),
body: new ListView.builder
(
itemCount: litems.length,
itemBuilder: (BuildContext ctxt, int index) {
return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),
onTap: () {
// begin of all IF statements
if (litems.contains("Totonto")){
Navigator.push(
ctxt,
MaterialPageRoute(
builder: (ctxt) => TorontoUniversitySection()
),
);
}
if (litems.contains("London")){
Navigator.push(
ctxt,
MaterialPageRoute(
builder: (ctxt) => LondonUniversitySection()
),
);
}
// end of all If statements
},
);
}
)
);
}
}
for example, when I press Toronto it will take me to LondonUniversitySection()
That is because in your if statements, you check whether your list contains Toronto/London and not if currently pressed one is Toronto/London. Changing litems.contains("x") to litems[index] == "x" will do the trick. Here's edited fragment:
return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),
onTap: () {
if (litems[index] == "Toronto") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => TorontoUniversitySection()),
);
} else if (litems[index] == "London") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => LondonUniversitySection()));
}
},
);
Also, I recommend using a switch or else-if for that, not a bunch of ifs.
Try onTap: litems.contains("Totonto")?
Navigator.push( ctxt, MaterialPageRoute( builder: (ctxt) => TorontoUniversitySection() ), )
: null
class _RegisterBodyState extends State<RegisterBody> {
FocusNode myFocusNode = new FocusNode();
FocusNode myFocusNode2 = new FocusNode();
void initState() {
super.initState();
myFocusNode = FocusNode();
myFocusNode2 = FocusNode();
}
#override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
myFocusNode2.dispose();
super.dispose();
}
Color color;
#override
Widget build(BuildContext context) {
return Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Register",
style: TextStyle(
color: Theme.of(context).primaryColor,
fontSize: 70.0,
fontWeight: FontWeight.bold,
),
),
Form(
child: Column(
children: [
TextFormField(
onTap: () {
setState(() {
color = Colors.red;
});
},
autofocus: true,
focusNode: myFocusNode,
decoration: InputDecoration(
icon: Icon(
Icons.supervised_user_circle,
size: 40.0,
),
labelText: "User Name",
labelStyle: TextStyle(
color:
myFocusNode.hasFocus ?color : Colors.yellow),
),
),
TextFormField(
focusNode: myFocusNode2,
onTap: () {
setState(() {
color = Colors.black;
});
},
autofocus: false,
decoration: InputDecoration(
icon: Icon(
Icons.supervised_user_circle,
size: 40.0,
),
labelText: "User Name",
labelStyle: TextStyle(
color: myFocusNode2.hasFocus ? color : Colors.teal,
),
),
),
],
))
],
),
),
);
}
}
I try to build a App with flutter and have a problem by building the navigation. I want to have a navigation like in the current version of youtube app. A Bottom Navigation Bar with three Pages and than for each Page sub Pages with an owen navigation stack. On all subpages it shoud be possible to change the main view and the app shoud save on witch subpage i where. Is that possible? I found no solution for that. I think it shoud be possible because its on the example page of material Design: https://material.io/design/components/bottom-navigation.html#behavior at the Point "Bottom navigation actions".
I would be so thankful for help!
I'd take a look at this code snippet for help.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_nit2018/navigarion_drawer.dart';
import 'package:my_nit2018/pages/app/blog/blog_page.dart';
import 'package:my_nit2018/pages/app/home/home_page.dart';
import 'package:my_nit2018/pages/app/library/library_page.dart';
import 'package:my_nit2018/pages/app/notifications/notifications_page.dart';
class MainApp extends StatefulWidget {
FirebaseUser user;
MainApp(this.user);
#override
_MainAppState createState() => new _MainAppState();
}
class _MainAppState extends State<MainApp> {
int i = 0;
var pages = [
new HomePage(),
new BlogPage(),
new LibraryPage(),
new NotificationsPage()
];
#override
Widget build(BuildContext context) {
return new Scaffold(
body: pages[i],
drawer: new AppNavigationDrawer(),
bottomNavigationBar: new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.photo_library),
title: new Text('Blog'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.book),
title: new Text('Library'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.notifications),
title: new Text('Notifications'),
),
],
currentIndex: i,
type: BottomNavigationBarType.fixed,
onTap: (index) {
setState(() {
i = index;
});
},
),
);
}
}
AppNavigationDrawer:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_nit2018/pages/app/app_state.dart';
import 'package:my_nit2018/pages/app/main_app.dart';
import 'package:my_nit2018/pages/app/profile/profile_page.dart';
import 'package:my_nit2018/pages/auth/login_page.dart';
class AppNavigationDrawer extends StatefulWidget {
#override
_AppNavigationDrawerState createState() => new
_AppNavigationDrawerState();
}
class _AppNavigationDrawerState extends State<AppNavigationDrawer> {
#override
Widget build(BuildContext context) {
final appState = AppState.of(context);
return new Drawer(
child: new ListView(
padding: EdgeInsets.zero,
children: <Widget>[
new DrawerHeader(
child: new Text('MyNiT App'),
decoration: new BoxDecoration(
color: Colors.blue,
),
),
new ListTile(
title: new Text('Todo List'),
leading: new Icon(Icons.list),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Subscriptions'),
leading: new Icon(Icons.subscriptions),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Activity'),
leading: new Icon(Icons.timelapse),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Profile'),
leading: new Icon(Icons.account_circle),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new AppState(
firebaseUser: appState.firebaseUser,
user: appState.user,
child: new ProfilePage(),
),
),
);
},
),
new ListTile(
title: new Text('Logout'),
leading: new Icon(Icons.exit_to_app),
onTap: () {
// Sign out user from app
FirebaseAuth.instance.signOut();
Navigator.of(context).pushAndRemoveUntil(
new MaterialPageRoute(builder: (context) => new LoginPage()),
ModalRoute.withName(null));
},
),
],
),
);
}
}
Try this Simple Bottom Bar
[import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>\[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
\];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>\[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
title: Text('School'),
),
\],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber\[800\],
onTap: _onItemTapped,
),
);
}
}][1]
Check this image for Sample