How to change AppBar's automaticallyImplyLeading property via a Consumer - flutter-web

As someone new to Flutter/Dart, I have a simplistic proof-of-concept web app (code provided below) where I've genuinely put the effort in to reading & prototyping but cannot quite get the code finished.
The app is a test of named routes. FirstScreen uses an ElevatedButton to jump to SecondScreen. SecondScreen can only return to FirstScreen via the Back arrow in SecondScreen's AppBar, but I also want the ability to dynamically hide that Back arrow if the app is started from SecondScreen, or enable it if the app is started from FirstScreen. Why ? Because the idea is to provide the option to run SecondScreen in a kiosk mode where the user's navigation is restricted to that one route of the app.
I designed the code to use a ChangeNotifier/Consumer approach using Flutter's "provider" package. The state is provided by the routedViaHome boolean (default is false) in RouteMonitor. The only time the boolean should be set true is if the app starts at FirstScreen and the user clicks the ElevatedButton to go to SecondScreen; that change is observed by SecondScreen and should be used to dynamically set its own AppBar 'automaticallyImplyLeading' property.
My question is this: the Consumer is correctly displaying the Text widget, but how do I ALSO get it to update the automaticallyImplyLeading property ? What am I missing please and/or have I needlessly complicated this ?
Thank you !
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => RouteMonitor(),
child: const MyApp(),
)
);
}
class RouteMonitor with ChangeNotifier {
bool routedViaHome = false;
void routeViaHome() {
routedViaHome = true;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => const FirstScreen(),
'/second': (context) => const SecondScreen(),
},
);
}
}
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Provider.of<RouteMonitor>(context, listen: false).routeViaHome();
Navigator.pushNamed(context, '/second');
//Navigator.pushReplacementNamed(context, '/second');
},
child: const Text('Launch screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Screen'),
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This is static data but no navigation'),
Consumer<RouteMonitor>(
builder: (context, routemonitor, child) => Text(
'${routemonitor.routedViaHome}',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
);
}
}

Related

The instance member 'name' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression [duplicate]

This question already has answers here:
Error: The instance member ... can't be accessed in an initializer
(4 answers)
Closed 4 months ago.
I always get this error when I use the String "name" to locate my Firestore docs. I don't understand why this is happening bc when I use "user.uid" it just works.
The instance member 'name' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
This is my code:
final user = FirebaseAuth.instance.currentUser!;
class Folder extends StatelessWidget {
Folder(this.name, {super.key});
final String name;
final Stream<QuerySnapshot> items = FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.collection('Folder')
.doc(name)
.collection('Items')
.snapshots();
#override
Widget build(BuildContext context) {
return Column(
children: [
// Title
Text(name, style: Theme.of(context).textTheme.headlineSmall),
// List with Items
StreamBuilder(
stream: items,
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final data = snapshot.requireData;
if (snapshot.hasData) {
return ListView.builder(
itemCount: data.size,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return ListTile(
title: Text(data.docs[index]['name']),
onTap: () {},
);
},
);
}
if (snapshot.hasError) {
return const Text("error");
}
return const Text("error");
},
),
],
);
}
}
And I pass the String from this StreamBuilder:
stream: folder,
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final data = snapshot.requireData;
if (snapshot.hasError) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(00.0),
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 100, top: 20),
itemCount: data.size,
itemBuilder: (context, index) {
return Folder(
data.docs[index]["name"].toString()
);
},
),
);
}
return const Center(child: CircularProgressIndicator());
},
),
You could just add a late modifier to the items variable. Like this:
late final Stream<QuerySnapshot> items = FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.collection('Folder')
.doc(name)
.collection('Items')
.snapshots();
To explain why this works: basically you can't use any instance variables when initializing other instance variables because they are all initialized when the class gets instantiated. When you add the late modifier, the variable will only be initialized when it's first used, meaning all the non-late variables will already be initialized.

(Flutter) How can I identify which ListTile in my ListView the user clicked the PopupMenuItem?

I have a ListView which holds ListTiles. Each tile represents a user of my users array. The trailing of a tile is a PopupMenuButton. When the user clicks on one PopupMenuItem, a function shall be called. So far so good. In the "onSelected" I would like to pass data of the corresponding user to a function.
Could anybody please give me a hint, how I should change the code to be able to do so?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:flutter/material.dart';
class UserListMobilePortrait extends StatelessWidget {
final List<QueryDocumentSnapshot> users;
const UserListMobilePortrait({
Key key,
this.users,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final HttpsCallable setRoleCallable = CloudFunctions.instance
.getHttpsCallable(functionName: 'setRoles')
..timeout = const Duration(seconds: 10);
final button = new PopupMenuButton(
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
child: const Text('Make Admin'), value: 'admin'),
new PopupMenuItem<String>(
child: const Text('Make Editor'), value: 'editor'),
],
onSelected: (selectedItem) async {
try {
final HttpsCallableResult result = await setRoleCallable.call(
<String, dynamic>{
//'user' shall represent the user of the clicked ListTile, but how to pass it?
'email': user.data()['email'],
'role': selectedItem,
'permission': 'grant'
},
);
print(result.data);
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
});
return ListView(
children: users
.map((user) => ListTile(
title: Text(
(user.data()['email'] != null) ? user.data()['email'] : ""),
subtitle: Row(
children: [
Text((user.data()['displayName'] != null)
? user.data()['displayName']
: ""),
Container(
width: 6,
),
user.data()['isAdmin'] == true
? Chip(
label: Text('admin'),
backgroundColor: Colors.orange[600],
shadowColor: Colors.orange[900],
)
: Text(''),
Container(
width: 6,
),
user.data()['isEditor'] == true
? Chip(
label: Text('editor'),
backgroundColor: Colors.blue[600],
shadowColor: Colors.blue[900],
)
: Text(''),
],
),
trailing: button,
))
.toList(),
);
}
}
understanding your problem a simple workaround will be to use a Listview Builder(And also using a ListView Builder will optmize the app for speed)
const List = ["Hello", "World", "Temp"]
ListView.builder(
itemBuilder: (context, index) {
//return (Your widget [a list tile preferably and use onTap(and access the index
in the function)])
return(ListTile(onTap:(){
print(List[index]);
//you can access the index and use the main list to get its following data
};
};
This will workout :)
My solution was moving the former final button to its own class. So I can pass the data to the constructor.
UserPopupMenuButton
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:flutter/material.dart';
class UserPopupMenuButton extends StatelessWidget {
final QueryDocumentSnapshot user;
const UserPopupMenuButton({
Key key,
this.user,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final HttpsCallable setRoleCallable = CloudFunctions.instance
.getHttpsCallable(functionName: 'setRoles')
..timeout = const Duration(seconds: 10);
return PopupMenuButton(
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
child: const Text('Make Admin'), value: 'admin'),
new PopupMenuItem<String>(
child: const Text('Make Editor'), value: 'editor'),
],
onSelected: (selectedItem) async {
try {
final HttpsCallableResult result = await setRoleCallable.call(
<String, dynamic>{
'email': user.data()['email'],
'role': selectedItem,
'permission': 'grant'
},
);
print(result.data);
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
});
}
}
And using it as the trailing for the ListTile:
trailing: UserPopupMenuButton(user: user),

Flutter show download failed with java.lang.IllegalArgumentException after downloading 100%

I am trying to make a wallpaper app to download images but it shows download failed when it completes download with error Couldn't find meta-data for provider with authority. I am downloading with flutter-downloader package.
Thanks.
java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority
sagarrawatuk.fotoApp.flutter_downloader.provider
class _ImagePathState extends State<ImagePath> {
String localPath;
Future<String> get localpath async {
final result = await Permission.storage.request();
if (result == PermissionStatus.granted) {
final localPath =
(await findLocalPath()) + Platform.pathSeparator + 'Download';
final savedDir = Directory(localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
return localPath;
} else
return null;
}
Future<String> findLocalPath() async {
final directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
return directory.path;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: myColor,
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
color: Colors.black,
),
actions: [
IconButton(
color: Colors.black,
icon: Icon(Icons.file_download),
onPressed: () async => DownloadTask(
taskId: await FlutterDownloader.enqueue(
url: widget.imgPath,
savedDir: await localpath,
showNotification: true)))
],
),
body: SizedBox.expand(
child: Container(
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Hero(
tag: widget.imgPath, child: Image.network(widget.imgPath)),
),
],
),
),
),
);
}
Add provider in your AndroidManifest.xml
<provider
android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
android:authorities="${applicationId}.flutter_downloader.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
See docs https://pub.dev/packages/flutter_downloader#android-integration

OAuth Acces Token Verification in node.js

I am working on a flutter app and would want to use facebook and google oauths to authenticate my users. Here is the code on the client side which works perfectly.
import 'package:flutter/material.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as JSON;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isLoggedIn = false;
Map userProfile;
final facebookLogin = FacebookLogin();
_loginWithFB() async {
final result = await facebookLogin.logIn(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final token = result.accessToken.token;
final graphResponse = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}');
final profile = JSON.jsonDecode(graphResponse.body);
print(profile);
setState(() {
userProfile = profile;
isLoggedIn = true;
});
break;
case FacebookLoginStatus.cancelledByUser:
setState(() => isLoggedIn = false);
break;
case FacebookLoginStatus.error:
setState(() => isLoggedIn = false);
break;
}
}
_logoutWithFB() {
facebookLogin.logOut().then((value) => setState(() => isLoggedIn = false));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: isLoggedIn
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.network(
"http://placehold.it/50x50",
height: 50.0,
width: 50.0,
),
SizedBox(
height: 50.0,
),
OutlineButton(
onPressed: _logoutWithFB,
child: Text('Logout'),
),
],
)
: OutlineButton(
onPressed: _loginWithFB,
child: Text('Facebook login'),
color: Colors.blueAccent,
),
),
);
}
}
The logic I want to use is for sign in, the user sign up with facebook or google, I get some basic info and ask the user to add some further information in another screen, then on submission the user info and the token are sent to the backend (which is a node.js api).\
On the back I want to verify the token received from the front end with facebook or google and if the profile id match the one received the user info received from the front end is saved, then a JWT would be created and sent to the front end.
My challenge now is how do I verify the oauth token on the node.js side.
User -> SignIn Facebook -> Token generated -> Token Sent to Backend -> Middleware Nodejs -> check user_id exist -> generate JWT -> sendBackTo clientSide.
It's very simple you have to create a middleware function in your back-end nodejs in this case.
const express = require("express");
const app = express();
//function that return JWT token
String check_user_id(req,res,next) async
{
var uid = req.params.uid
//Query database check if userIdexist or not
check_db(uid)
//if it exist
next();
return GenerateJwt(userId)
else
{
//Signup the userid
SignUp(userId);
//generateJWT
next();
return GenerateJwt(userId);
}
}
app.get('/check_uid/:uid',check_user_id,(res,req,next) =>
{
res.send({'message':'verified'});
}

Displaying questions from API one at a time in Flutter

i want to display the questions i get from an API one by one. I call the API, parse and store the data, but i don't know how to display each question separately. I can put them in a list view but that's about it. I have a widget with FutureBuilder that calls the API, and i'm currently trying to send data to another widget and manipulate it there using another FutureBuilder (so that i don't keep calling the API when i iterate through the list of questions to display them). I have an integer to keep track of the current position. How should i go about doing this?
Part of the code:
Here i'm trying to send the data to another widget.
FutureBuilder<Reply>(
future: questions(token, id),
builder: (context, snapshot) {
if (snapshot.hasError) {
print('Error : ${snapshot.error}'); //show error on the terminal
return Text('Error : ${snapshot.error}'); //show error on the app
} else if (snapshot.hasData) {
reply = snapshot.data;
return Show_Questions(reply: reply,);
} else {
return Center(child: CircularProgressIndicator()); //else display a loading indicator
} //loading indicator
}
),
Any help is appreciated. I can post more code if needed.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new FutureBuilder(
future: questions(token, id),
initialData: [],
builder: (context, snapshot) {
return createListView(context, snapshot);
}),
);
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
var values = snapshot.data;
return ListView.builder(
itemCount: values == null ? 0 : values.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
});
},
child: Column(
children: <Widget>[
new ListTile(
title: Text(values[index]),
),
Divider(
height: 2.0,
),
],
),
);
},
);
}
}
hopefully help you :)

Resources