Flutter screen navigating back when updating firestore document - flutter

I'm have successfully displayed list of users in ListView using StreamBuilder. But when I'm updating user document in firestore, screen in my mobile app is automatically navigating back.
This is my screens flow. Login -> Home -> ManageUsers -> UserDetails.
By using below code, I created a list in Manage Users screen. Now I'm trying to update user first name in firebase console. After updating the data ManageUsers screen is closing.
Screen Rec
Widget build(BuildContext context) {
return new StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
if (snapshot.hasError)
return Center(child: new Text('Error: ${snapshot.error}'));
final int itemsCount = snapshot.data.documents.length;
switch (snapshot.connectionState) {
case ConnectionState.none:
// TODO: Handle this case.
return new CircularProgressIndicator();
break;
case ConnectionState.waiting:
// TODO: Handle this case.
return new CircularProgressIndicator();
break;
default:
return new ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: itemsCount,
addAutomaticKeepAlives: true,
itemBuilder: (BuildContext context, int index) {
final DocumentSnapshot document =
snapshot.data.documents[index];
return new ListTile(
title: new Text(document['first_name']),
subtitle: new Text(document['last_name']),
onTap: () => {openUserDetailsScreen(document, context)},
);
},
);
}
},
);
}
Actually it should refresh the data in the same screen instead of navigating back. Am I doing anything wrong in building the list.
Home Screen Code
class HomeScreen extends StatefulWidget {
HomeScreen({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomeScreenState createState() => _MyHomeScreenState();
}
class _MyHomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
automaticallyImplyLeading: false,
leading: Builder(
builder: (context) =>
IconButton(
icon: new Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
drawer: MyDrawer(widget.title),
body: Center(
child: Text("Home Screen"),
),
);
}
#override
void initState() {
print('in home page ${globals.loggedInUser.firstName}');
}
}
From home page I'm navigating to ManageUsers screen via drawer. Here is the code for drawer.
class MyDrawer extends StatelessWidget {
MyDrawer(this.currentPage);
final String currentPage;
bool isAdmin = true;
#override
Widget build(BuildContext context) {
var currentDrawer = Provider.of<DrawerStateInfo>(context).getCurrentDrawer;
return Drawer(
child: ListView(
children: <Widget>[
_CustomListTile(
currentPage, globals.HOME_MENU_TITLE, currentDrawer),
_CustomListTile(
currentPage, globals.LOGIN_MENU_TITLE, currentDrawer),
ConditionalBuilder(
condition: isAdmin,
builder: (context) => _CustomListTile(currentPage,
globals.MANAGE_USERS_MENU_TITLE, currentDrawer),
)
],
),
);
}
}
class _CustomListTile extends StatelessWidget {
final String currentPage;
final String tileTitle;
final currentDrawer;
_CustomListTile(this.currentPage, this.tileTitle, this.currentDrawer);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
tileTitle,
style: currentDrawer == 1
? TextStyle(fontWeight: FontWeight.bold)
: TextStyle(fontWeight: FontWeight.normal),
),
onTap: () {
Navigator.of(context).pop();
if (this.currentPage == tileTitle) return;
Provider.of<DrawerStateInfo>(context).setCurrentDrawer(1);
switch (tileTitle) {
case globals.HOME_MENU_TITLE:
{
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => HomeScreen(
title: globals.HOME_MENU_TITLE,
)));
break;
}
case globals.LOGIN_MENU_TITLE:
{
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => LoginScreen(
title: globals.LOGIN_MENU_TITLE,
)));
break;
}
case globals.MANAGE_USERS_MENU_TITLE:
{
Navigator.of(context).pushNamed("/ManageUsers");
break;
}
default:
{
break;
}
}
});
}
}

ListView StreamBuilder means it will listening to your collection.
Please remove the listener when you move to next screen.

This piece of code looks wrong to me:
Provider.of<DrawerStateInfo>(context).setCurrentDrawer(1);
You should have something like an enum or even the tileTitle to use as the saved state for the currently selected option on the drawer, otherwise, you only know there is a selected option, but not exactly which one.
This leads you to this crazy behavior of calling incorrect routes.
Try something like this
class MyDrawer extends StatelessWidget {
MyDrawer(this.currentPage);
final String currentPage;
bool isAdmin = true;
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: <Widget>[
_CustomListTile(currentPage, globals.HOME_MENU_TITLE),
_CustomListTile(currentPage, globals.LOGIN_MENU_TITLE),
isAdmin
? _CustomListTile(currentPage, globals.MANAGE_USERS_MENU_TITLE)
: Container(),
],
),
);
}
}
class _CustomListTile extends StatelessWidget {
final String currentPage;
final String tileTitle;
_CustomListTile(
this.currentPage,
this.tileTitle,
);
#override
Widget build(BuildContext context) {
return Consumer<DrawerStateInfo>(
builder: (context, draweStateInfo, _) {
final currentSelectedItem = draweStateInfo.getCurrentDrawer();
return ListTile(
title: Text(
tileTitle,
style: currentSelectedItem == tileTitle
? TextStyle(fontWeight: FontWeight.bold)
: TextStyle(fontWeight: FontWeight.normal),
),
onTap: () {
Navigator.of(context).pop();
if (currentSelectedItem == tileTitle) return;
draweStateInfo.setCurrentDrawer(tileTitle);
switch (currentSelectedItem) {
case globals.HOME_MENU_TITLE:
{
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => HomeScreen(
title: globals.HOME_MENU_TITLE,
)));
break;
}
case globals.LOGIN_MENU_TITLE:
{
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => LoginScreen(
title: globals.LOGIN_MENU_TITLE,
)));
break;
}
case globals.MANAGE_USERS_MENU_TITLE:
{
Navigator.of(context).pushNamed("/ManageUsers");
break;
}
default:
{
break;
}
}
});
},
);
}
}

Related

Opening a screen out the result of a statement

enter code hereI want to open a screen to add extra information if it is not set yet. So after the user is logged in I check if the extra info is set. If not I want it to go to a screen to fill in the info. If the user is done it should go to a "Homescreen". If the user info is already set it should immediately go to the home screen.
I already tried to just go to the extra info form and then Navigator.push to the home screen but then it has difficulties with logging out. I searched for a long time but can not find anything.
class CampPage extends StatelessWidget {
final String email;
final String uid;
const CampPage({super.key, required this.email, required this.uid});
#override
Widget build(BuildContext context) {
return FutureBuilder(
// ignore: unrelated_type_equality_checks
future: context.read<UserProvider>().exists(uid) == true
? null
: Future.delayed(Duration.zero, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewUserPage(email: email, userId: uid),
),
);
}),
builder: (context, snapshot) => Scaffold(
drawer: const DrawerHomePage(),
appBar: AppBar(
title: const Text("Camp Page"),
),
body: Column(
children: const [
Text("nieuwe features"),
],
),
),
);
}
}
this is one of the things I try but the NewUserPage always pops up and I only want it to pop up if context.read<UserProvider>().exists(uid) == false
also the solution mentioned does not work for me. I think because there is a screen in between the login and logout (The form screen) the logout function does not work properly.
`
class UserPage extends StatelessWidget {
const UserPage({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: ElevatedButton(
child: const Text("Submit"),
onPressed: () {
//Log out of Firestore Authentication
},
),
);
}
}
class NewForm extends StatelessWidget {
const NewForm({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: ElevatedButton(
child: const Text("Submit"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UserPage()),
);
},
),
);
}
}
Widget build(BuildContext context) {
return FutureBuilder(
future: context.read<UserProvider>().exists(uid)
builder: (context, snapshot) {
if (snapshot.hasdata){
if (snapshot.data == true) {
return const UserPage();
} else {
return const NewForm();
}
}
else // show a proggress bar
}
);
}
`
Does someone still have another solution?
I think you should do this:
Widget build(BuildContext context) {
return FutureBuilder(
future: context.read<UserProvider>().exists(uid)
builder: (context, snapshot) {
if (snapshot.hasdata){
if (snapshot.data == true) // then the user exist
else // the user doesn't exist
}
else // show a proggress bar
}
);
}

I take the data from Firestore and show it with a list (card). When I click on the card, I want it to detail the data on a new page

I get the data from Firestore, but because a text is too long, I cannot show it with a card. I want to be directed to a new page using ontap and see the information on that card in more detail on that page.
how do i do this
dynamic resultant = await DatabaseManager().getUsersList();
if (resultant == null) {
print('Unable to retrieve');
} else {
setState(() {
userProfilesList = resultant;
});
}
}
updateData(String sesAd, String sesKayit, int time, String userID,
String kelimesayisi) async {
await DatabaseManager().updateUserList(sesAd, sesKayit, time, userID);
fetchDatabaseList();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Langrec'),
),
body: ListView.builder(
itemCount: userProfilesList.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
);
},
title: Padding(
padding: const EdgeInsets.all(16.0),
child: Stack(
children: <Widget>[
Container(
Text(
userProfilesList[index]()['sesAd'],
style: TextStyle(
color: Colors.white,
fontFamily: 'Avenir',
),
),'''
You can do so by
DetailPage
class DetailPage extends StatefulWidget {
final DocumentSnapshot doc;
DetailPage({this.doc});
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Container();
}
}
Now from your onTap you can navigate to the detail page by the following code
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(doc: userProfilesList,),));
To access the document you can use widget.doc which is a document snapshot object.
Ex:
Text('${widget.doc["Text"]}'),

how to trigger search automatically when using SearchDelegate buildSuggestions in flutter

Now I am using SearchDelegate in flutter 2.0.1, this is my buildSuggestions code:
#override
Widget buildSuggestions(BuildContext context) {
var channelRequest = new ChannelRequest(pageNum: 1, pageSize: 10, name: query);
if (query.isEmpty) {
return Container();
}
return FutureBuilder(
future: ChannelAction.fetchSuggestion(channelRequest),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<ChannelSuggestion> suggestions = snapshot.data;
return buildSuggestionComponent(suggestions, context);
} else {
return Text("");
}
});
}
Widget buildSuggestionComponent(List<ChannelSuggestion> suggestions, BuildContext context) {
return ListView.builder(
itemCount: suggestions.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${suggestions[index].name}'),
onTap: () async {
query = '${suggestions[index].name}';
},
);
},
);
}
when select the recommand text, I want to automatically trigger search event(when I click the suggestion text, trigger the search, fetch data from server side and render the result to UI) so I do not need to click search button. this is my search code:
#override
Widget buildResults(BuildContext context) {
var channelRequest = new ChannelRequest(pageNum: 1, pageSize: 10, name: query);
return buildResultImpl(channelRequest);
}
Widget buildResultImpl(ChannelRequest channelRequest) {
return FutureBuilder(
future: ChannelAction.searchChannel(channelRequest),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<Channel> channels = snapshot.data;
return buildResultsComponent(channels, context);
} else {
return Text("");
}
return Center(child: CircularProgressIndicator());
});
}
what should I do to implement it? I have tried invoke buildResults function in buildSuggestionComponent but it seems not work.
To update the data based on the query, you can make an API call to get the result when clicking on a suggestion, then use a StreamController to stream the results to the buildResults() method and call showResults().
I'm creating a simple app here for demonstration:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final _controller = StreamController.broadcast();
#override
dispose() {
super.dispose();
_controller.close();
}
Future<void> _showSearch() async {
await showSearch(
context: context,
delegate: TheSearch(context: context, controller: _controller),
query: "any query",
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Search Demo"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: _showSearch,
),
],
),
);
}
}
class TheSearch extends SearchDelegate<String> {
TheSearch({this.context, this.controller});
BuildContext context;
StreamController controller;
final suggestions =
List<String>.generate(10, (index) => 'Suggestion ${index + 1}');
#override
List<Widget> buildActions(BuildContext context) {
return [IconButton(icon: Icon(Icons.clear), onPressed: () => query = "")];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
},
);
}
#override
Widget buildResults(BuildContext context) {
return StreamBuilder(
stream: controller.stream,
builder: (context, snapshot) {
if (!snapshot.hasData)
return Container(
child: Center(
child: Text('Empty result'),
));
return Column(
children: List<Widget>.generate(
snapshot.data.length,
(index) => ListTile(
onTap: () => close(context, snapshot.data[index]),
title: Text(snapshot.data[index]),
),
),
);
},
);
}
#override
Widget buildSuggestions(BuildContext context) {
final _suggestions = query.isEmpty ? suggestions : [];
return ListView.builder(
itemCount: _suggestions.length,
itemBuilder: (content, index) => ListTile(
onTap: () {
query = _suggestions[index];
// Make your API call to get the result
// Here I'm using a sample result
controller.add(sampleResult);
showResults(context);
},
title: Text(_suggestions[index])),
);
}
}
final List<String> sampleResult =
List<String>.generate(10, (index) => 'Result ${index + 1}');
I have done it through a simple workaround
Simply add this line after your database call
query = query
But be careful of the call looping

Using search delegate for a listview generated from Future

Here is my listview generated from a Future from a json file.
class _ChorusPage extends State<ChorusPage> {
static Future<List<Chorus>> getList() async {
var data = await rootBundle.loadString('assets/chorusJson.json');
var jsonMap = json.decode(data); // cast<Map<String, dynamic>>();
List<Chorus> choruses = [];
for (var c in jsonMap) {
Chorus chorus = Chorus.fromJson(c);
choruses.add(chorus);
}
// var = User.fromJson(parsedJson);
// choruses = jsonMap.map<Chorus>((json) => Chorus.fromJson(json)).toList();
print(choruses.length);
return choruses;
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Chorus'), actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {})
]),
body: Container(
child: FutureBuilder(
future: getList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(child: CircularProgressIndicator()));
} else {
return ListView.builder(
itemCount: snapshot.data.length, // + 1,
itemBuilder: (BuildContext context, int index) {
return _listItem(index, snapshot);
});
}
})),
);
}
I am trying to implement a search function using the search delegate. The tutorial I am watching searches a List (https://www.youtube.com/watch?v=FPcl1tu0gDs&t=444s). What I have here is a Future. I am wondering how do you convert a future into a List. Or is there any other workaround.
class DataSearch extends SearchDelegate<String> {
Future<List<Chorus>> chorusList = _ChorusPage.getList();
// ????????????????????? How do I convert.
#override
List<Widget> buildActions(BuildContext context) {
// actions for app bar
return [IconButton(icon: Icon(Icons.clear), onPressed: () {})];
}
#override
Widget buildLeading(BuildContext context) {
// leading icon on the left of the app bar
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {});
}
#override
Widget buildResults(BuildContext context) {
// show ssome result based on the selection
throw UnimplementedError();
}
#override
Widget buildSuggestions(BuildContext context) {
/*
final suggestionList = query.isEmpty ? recentChorus : chorus;
return ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text(suggestList[chorus]),
),
itemCount: suggestionList.length,
);
// show when someone searches for
*/
}
}
In my opinion you should set your chorusList and call somewhere your getList method with the .then method store the value inside your chorusList.
List<Chorus> chorusList;
_ChorusPage.getList().then((value) => chorusList);

Flutter rebuild parent screen with provider on navigator push

I want to create a license validation system for my application in order to activate it if a license is entered or already present.
If when starting the application the license does not exist then I display a page which allows me to scan it by QR code.
If the scanned license is valid then I push a success page with a button on it that allows me to unlock the application. When I click on this button I want to close my success page and rebuild my application with the homepage of the application unlocked.
This works up to the success page. When I click on my button to unblock the app, I can't rebuild the parent page with the unblock app.
MyApp: This change choose the screen if I have a license or not.
class AppScreen extends StatelessWidget {
const AppScreen({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Impact',
debugShowCheckedModeBanner: false,
theme: AppTheme().data,
home: ChangeNotifierProvider<LicenseNotifier>(
create: (BuildContext context) => LicenseNotifier(),
child: Consumer(
builder: (context, LicenseNotifier license, _) {
return license.showScreenWithLicenseState();
},
),
),
);
}
}
My license notifier:
class LicenseNotifier with ChangeNotifier {
LicenseState state = LicenseState.Uninitialized;
String getLicenseInApp;
String licenseScanned;
String personnalKey;
final String _scanBarColor = "#f57873";
LicenseNotifier(){
personnalKey = "1010";
_checkIfAppIsUnlocked();
}
Future<void> _checkIfAppIsUnlocked() async {
if (getLicenseInApp != null) {
state = LicenseState.Authenticated;
}
else{
state = LicenseState.Unauthenticated;
}
notifyListeners();
}
Future scanQRCode(BuildContext context) async{
await FlutterBarcodeScanner.scanBarcode(_scanBarColor, "Cancel", true, ScanMode.QR).then((value) {
licenseScanned = value.toString();
});
licenseValidator(context);
}
void licenseValidator(BuildContext context){
if(licenseScanned == personnalKey){
showSuccessLicenseScreen(context);
}
notifyListeners();
}
void showSuccessLicenseScreen(BuildContext context){
Navigator.push(context, MaterialPageRoute(
builder: (context) => ChangeNotifierProvider<LicenseNotifier>(
create: (BuildContext context) => LicenseNotifier(),
child: LicenseSuccessScreen(title: "Valid license")
),
));
}
activateApp(BuildContext context) {
Navigator.pop(context);
state = LicenseState.Authenticated;
notifyListeners();
}
showScreenWithLicenseState(){
switch (state) {
case LicenseState.Uninitialized:
return SplashScreen();
break;
case LicenseState.Unauthenticated:
case LicenseState.Authenticating:
return LicenseActivationScreen(title: "Activate license");
break;
case LicenseState.Authenticated:
return ChangeNotifierProvider<BottomNavigationBarNotifier>(
create: (BuildContext context) => BottomNavigationBarNotifier(),
child: NavigationBarScreen(),
);
break;
}
return null;
}
}
My success screen: When I scan a valid license
class LicenseSuccessScreen extends StatelessWidget{
final String title;
const LicenseSuccessScreen({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context)
{
return GestureDetector(
onTap: (() => FocusScope.of(context).requestFocus(FocusNode())),
child: Scaffold(
appBar: AppBar(
backgroundColor: AppColors.colorContrastGreen,
elevation: 0,
centerTitle: true,
title: Text(title),
),
body : _buildBody(context),
),
);
}
Widget _buildBody(BuildContext context)
{
var _licenseProvider = Provider.of<LicenseNotifier>(context);
return Container(
color: AppColors.colorContrastGreen,
padding: EdgeInsets.symmetric(horizontal: AppUi.RATIO * 5),
height: double.infinity,
child: Column(
children: [
ContainerComponent(
background: AppColors.colorBgLight,
alignement: CrossAxisAlignment.center,
children: [
ButtonComponent.primary(
context: context,
text: "Débloquer",
onPressed: () async{
_licenseProvider.activateApp(context);
},
),
],
),
],
),
);
}
}
So when I click on my button who call "activateApp" in notifier, the success screen closes but I haven't my application content. It just show the LicenseActivationScreen. How to resolve this problem ?