I'm having issues using Shared Preferences on another page - flutter

I have been having issues retrieving the "username" String saved in Shared Preferences (from the Settings page) for the home page text field (~Line 60 main.dart). I have tried a few methods to retrieve it, but so far I haven't had any luck with trying to grab it. The last attempt I tried was using '$user' (~Line 29), but I still haven't had any luck. I'm still very new to Flutter programming, but I had assumed you could access Shared Preferences data globally as long as you had the Key. So far when I tried using the methods I saw online and in documentation I had no luck transferring the data. Thank you for your help!
main.dart
import 'package:bit/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:bit/saved_data.dart';
void main() {
runApp(MaterialApp(
title: 'App',
themeMode: ThemeMode.system,
theme: MyThemes.lightTheme,
darkTheme: MyThemes.darkTheme,
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
? 'Dark Theme'
: 'Light Theme';
final user = ''; // Empty String Line 29
var scaffold = Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
// Body Home Page Beginning
body: SingleChildScrollView(
child: Center(
child: Text('Hello $theme!'),
)),
// Body Home Page End
drawer: Drawer(
// Drawer Beginning
child: ListView(
children: [
// Drawer Header
DrawerHeader(
decoration: const BoxDecoration(
color: Colors.blue,
),
child: Stack(
children: const [
Align(
alignment: Alignment.centerLeft,
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 50.0,
)),
Align(
alignment: Alignment.centerRight,
child: Text('$user', // Area To Input Text Line 60
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
)),
Align(
alignment: Alignment(1, 0.3),
child: Text(
'Supporter',
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
),
))
],
),
),
// Drawer List
ListTile(
title: const Text('Settings'),
subtitle: const Text('Account Info & Settings'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Settings()),
);
},
trailing: const Icon(Icons.arrow_forward_ios_rounded),
),
],
),
),
// Drawer End
);
return MaterialApp(
title: 'App',
themeMode: ThemeMode.system,
theme: MyThemes.lightTheme,
darkTheme: MyThemes.darkTheme,
home: scaffold,
);
}
}
// Settings Page & Account Information
class Settings extends StatefulWidget {
Settings({Key? key}) : super(key: key);
#override
State<Settings> createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
final _preferencesService = PreferencesService();
final _usernameController = TextEditingController();
void initState() {
super.initState();
_populateFields();
}
void _populateFields() async {
final settings = await _preferencesService.getSettings();
setState(() {
_usernameController.text = settings.username;
});
}
#override
Widget build(BuildContext context) {
final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
? 'Dark Theme'
: 'Light Theme';
return Scaffold(
appBar: AppBar(
title: const Text(
'Settings'), /* actions: <Widget>[
IconButton(
onPressed: () async {
_saveSettings;
},
icon: const Icon(Icons.save),
tooltip: 'Save Settings')
] */
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
child: Column(
children: [
Column(
// Account
children: [
const Padding(
padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
child: Text('Account Information',
style: TextStyle(
fontSize: 17.0,
))),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: TextField(
controller: _usernameController,
inputFormatters: [LengthLimitingTextInputFormatter(25)],
decoration: InputDecoration(
hintText: 'Username',
labelText: 'Username',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0)),
),
),
),
],
),
Container(
child: Column(
// App Settings
children: [
// SwitchListTile(value: DarkMode, onChanged: Light => Dark => Light)
// ChangeThemeButtonWidget(),
TextButton(
onPressed: _saveSettings,
child: const Text('Save Settings'),
)
],
),
),
],
),
)));
}
void _saveSettings() {
final newSettings = SettingsModal(
username: _usernameController.text,
);
print(newSettings);
print(_usernameController.text);
_preferencesService.saveSettings(newSettings);
}
}
shared_preferences.dart
import 'package:bit/main.dart';
import 'package:bit/saved_data.dart';
import 'package:shared_preferences/shared_preferences.dart';
class PreferencesService {
Future saveSettings(SettingsModal settings) async {
final preferences = await SharedPreferences.getInstance();
await preferences.setString('username', settings.username);
print('Saved Settings');
}
Future<SettingsModal> getSettings() async {
final preferences = await SharedPreferences.getInstance();
final username = preferences.getString('username')!;
return SettingsModal(
username: username,
);
}
}
saved_data.dart
import 'package:shared_preferences/shared_preferences.dart';
import 'package:bit/main.dart';
class SettingsModal {
final String username;
SettingsModal({
required this.username,
});
}

The issue is coming because, you like to use user which is not a constant. While adding const on Stack's children as Constance, which can be happened in this case, remove const and it won't show any errors.
child: Stack(
children: [
Align(
alignment: Alignment.centerLeft,
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 50.0,
)),
Align(
alignment: Alignment.centerRight,
child: Text(
user,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
)),
],
),
To receive data from future(SharedPreference) we need to wait.
You can use FutureBuilder in this case.
We can provide default value instead of using ! and make it static .
static Future<SettingsModal> getSettings() async {
final preferences = await SharedPreferences.getInstance();
final username = preferences.getString('username') ?? "Not found";
return SettingsModal(
username: username,
);
}
Use PreferencesService.getSettings(), to get data.
Align(
alignment: Alignment.centerRight,
child: FutureBuilder<SettingsModal>(
future: PreferencesService.getSettings(),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.connectionState ==
ConnectionState.done) {
return Text(
snapshot.data!.username,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
);
}
/// better to handle other cases, included on answer
return CircularProgressIndicator();
},
)),
More about FutureBuilder

Related

How do I fix my problem with routes in Flutter?

good evening. I am currently doing a To-do List in Flutter and I want to pass the Title of my List and the Description of my List when I click on a new screen but upon setting up Routes and and declaring the values on my next, it shows the "2 positional arguments expected, but 0 found" on the routes I've set up. Here are my codes:
Here is my 1st screen:
import 'package:flutter/material.dart';
import 'package:todo_list/details.dart';
import 'package:todo_list/note.dart';
class MyApp extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const MyApp(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
DetailsPage.routeName: (ctx) => DetailsPage(),
},
home: CustomListTile(
text: text,
number: number,
listDescription: listDescription,
),
);
}
}
class CustomListTile extends StatelessWidget {
final String text;
final int number;
final String listDescription;
const CustomListTile(
{super.key,
required this.text,
required this.number,
required this.listDescription});
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, DetailsPage.routeName,
arguments: Note(title: text, description: listDescription));
},
/* onTap: () {
Widget okButton = TextButton(
child: const Text("CLOSE"),
onPressed: () {
Navigator.of(context).pop();
},
);
AlertDialog alert = AlertDialog(
title: Text(text),
content: Text('This item in the list contains $listDescription'),
actions: [
okButton,
]);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
});
}, */
child: Padding(
padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("$number. $text",
style: const TextStyle(
fontSize: 20,
)),
const Icon(Icons.chevron_right)
],
),
Text(
listDescription,
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
const Divider()
],
),
),
);
}
}
and here is my 2nd screen:
import 'package:flutter/material.dart';
import 'note.dart';
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
#override
State<DetailsPage> createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
late Note params;
#override
void didChangeDependencies() {
params = ModalRoute.of(context)!.settings.arguments! as Note;
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
Widget titleSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(bottom: 0),
child: Text(
params.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
),
],
),
),
],
),
);
Color color = Theme.of(context).primaryColor;
Widget buttonSection = Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(
color,
Icons.edit,
'EDIT',
),
_buildButtonColumn(color, Icons.delete, 'DELETE'),
],
);
Widget textSection = Padding(
padding: const EdgeInsets.all(20),
child: Text(
params.description,
softWrap: true,
),
);
return MaterialApp(
title: 'Layout for a New Screen',
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(params.title),
),
body: ListView(
children: [
Image.asset(
'lib/images/placeholder.jpg',
width: 600,
height: 240,
fit: BoxFit.cover,
),
titleSection,
buttonSection,
textSection,
],
),
),
);
}
Column _buildButtonColumn(
Color color,
IconData icon,
String label,
) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
}
/* return Scaffold(
appBar: AppBar(title: Text(text)),
body: Center(
child: Row(
children: [Text(description)],
),
));
}
} */
How do I make it so that the data I'll pass such as the Title and the Description will appear on the 2nd screen without the error "2 positional argument(s) expected, but 0 found.
Try adding the missing arguments." appearing.
I tried the Quick Fixes on VS Code such as adding a const modifier but I think the const modifier wouldn't do a fix since both data I'm trying to pass are dynamic and may change from time to time.
As you've define details page
class DetailsPage extends StatefulWidget {
static const String routeName = "/details";
final String text;
final String listDescription;
const DetailsPage(this.text, this.listDescription, {super.key});
You need to pass two string as positional argument.
So it can be
routes: {
DetailsPage.routeName: (ctx) => DetailsPage("text","description"),
},
also while you are using route arguments, you can remove theses from widget class and just accept from state class context with ModalRoute.
You can check this example and development/ui/navigation .

flutter transfer data (color) to create a new widget

I'm creating a calendar app. The problem that I'm now facing is that I want to create a new user of the calendar. The user has the properties (which are now important) image, name and color.
I created a new File For the property color, in which the color can be changed. But I don't know how I can transfer the new color in the other file, so that I can use it to create the user.
I think it is possible to use the Material page route, but perhaps there is a more elegant way to handle this.
Does someone have an idea to handle this in a easy way?
UserSetScreen:
import 'package:calendar_vertical/screens/users_show_screen.dart';
import 'package:calendar_vertical/widgets/color_choose.dart';
import 'package:calendar_vertical/widgets/image_input.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class UserSetScreen extends StatefulWidget {
static const routeName = '/userSetScreen';
#override
State<UserSetScreen> createState() => _UserSetScreenState();
}
class _UserSetScreenState extends State<UserSetScreen> {
final _titleController = TextEditingController();
static const values = <String>[
'Administrator',
'normaler Nutzer',
'eingeschränkter Nutzer'
];
String selectedValue = values.first;
void _saveValues(User user) {
final neuerNutzer = User(
id: DateTime.now().toString(),
name: _titleController.text,
color: Colors.amber,
setAppointments: false,
administrator: false,
);
}
#override
Widget build(BuildContext context) {
final colorData = Provider.of<ColorChoose>(context);
return Scaffold(
appBar: AppBar(
title: Text('Person hinzufügen'),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(UsersShowScreen.routeName);
},
icon: Icon(Icons.people),
),
],
),
body: Column(
children: [
Center(
child: ImageInput(),
),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextField(
decoration: InputDecoration(labelText: 'Name'),
controller: _titleController,
),
ColorChoose(),
//CheckboxListTile(
// value: value,
// onChanged: (value) => setState(() => this.value = value!),
// title: Text('Administrator'),
// controlAffinity: ListTileControlAffinity.leading,
//)
],
),
),
))
],
),
);
}
ColorChoose:
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
class ColorChoose extends StatefulWidget {
#override
State<ColorChoose> createState() => _ColorChooseState();
}
class _ColorChooseState extends State<ColorChoose> {
Color currentColor = Colors.white;
#override
Widget build(BuildContext context) {
return Row(
children: [
Text('Farbe: '),
Container(
decoration: BoxDecoration(
color: currentColor,
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0),
margin: EdgeInsets.only(left: 10.0),
),
Spacer(),
ElevatedButton(
onPressed: () => _showColorPicker(context),
child: Text(
'Farbe ändern',
),
),
],
);
}
void _showColorPicker(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Farbe wählen'),
titlePadding: const EdgeInsets.all(0.0),
contentPadding: const EdgeInsets.all(0.0),
content: SingleChildScrollView(
child: Wrap(
children: [
Container(
width: 300,
height: 300,
child: BlockPicker(
pickerColor: currentColor,
onColorChanged: (color) => setState(
() => this.currentColor = color,
),
),
)
],
),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Close'),
)
],
),
);
}
}
Thank you very much.
Best regards
Patrick
I guess the best variant is to use GetX or another state manager.
Another way - to choose color right from the user screen, showing a dialog.
Finally you can pass valuenotifier to your color ColorChoose widget.

Flutter - Find cards by names

I am new to flutter and I have a program that shows several cards and I have a question about how to make a card finder, I am using this code:
_card(
String phrase,
) {
return SliverToBoxAdapter(
child: Card(
margin: EdgeInsets.only(right: 50, left: 50, top: 20),
child: InkWell(
onTap: () {},
child: Column(children: <Widget>[
SizedBox(height: 15.0),
Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800]),
),
),
SizedBox(height: 15.0),
]),
),
),
);
}
and I use this to make the various cards:
return Scaffold(
body: Stack(children: [
CustomScrollView(physics: BouncingScrollPhysics(), slivers: <Widget>[
_card('Abrir'),
_card('Alzar'),
_card('Aprender'),
_card('Caer'),
_card('Cerrar'),
_card('Cocinar'),
_card('Correr'),
_card('Cortar'),
_card('Enseñar'),
_card('Estar'),
_card('Hay'),
_card('Levantarse'),
_card('Mirar'),
_card('Oler'),
_card('Saltar'),
_card('Sentar'),
_card('Ser'),
_card('Tocar'),
_card('Tomar'),
_card('Tropezar'),
]),
]),
);
I really appreciate any help, thanks
Here is a solution using:
hooks_riverpod for State Management
fuzzy for fuzzy search
Full source code for easy copy-paste
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fuzzy/fuzzy.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final phrases = useProvider(filteredPhrasesProvider);
return Scaffold(
body: ListView(
physics: BouncingScrollPhysics(),
children: [
TextField(
autofocus: true,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Search',
),
onChanged: (value) =>
context.read(searchTermsProvider).state = value,
),
...phrases.map((phrase) => _Card(phrase: phrase)).toList(),
],
),
);
}
}
class _Card extends StatelessWidget {
final String phrase;
const _Card({
Key key,
this.phrase,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10.0),
child: InkWell(
onTap: () {},
child: Padding(
padding: EdgeInsets.all(15.0),
child: Text(
phrase,
style: TextStyle(
fontFamily: 'Circular',
fontSize: 17.0,
color: Colors.grey[800],
),
),
),
),
);
}
}
final searchTermsProvider = StateProvider<String>((ref) => '');
final phrasesProvider = Provider<List<String>>(
(ref) => [
'Abrir',
'Alzar',
'Aprender',
'Caer',
'Cerrar',
'Cocinar',
'Correr',
'Cortar',
'Enseñar',
'Estar',
'Hay',
'Levantarse',
'Mirar',
'Oler',
'Saltar',
'Sentar',
'Ser',
'Tocar',
'Tomar',
'Tropezar',
],
);
final filteredPhrasesProvider = Provider<List<String>>((ref) {
final phrases = ref.watch(phrasesProvider);
final searchTerms = ref.watch(searchTermsProvider).state;
return searchTerms.isEmpty
? phrases
: Fuzzy<String>(phrases, options: FuzzyOptions(threshold: .4))
.search(searchTerms)
.map((result) => result.item)
.toList();
});
First you must change the logic of your code, create a List and then create the cards, so that the search engine works with the list
Create list:
final List<String> actions = ["Abrir", "Alzar", "Enseñar", "Sentar", "Mirar"];
Next, use List.generate or List.builder to create cards in the slivers
return Scaffold(
body: Stack(children: [
CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: List.generate(actions.length, (i) => _cards(actions[i])
),
]),
);
Finally in your seacher, use this logic, the "contains" is optional, you can change the logic in the if
void search(String data) {
for(int i = 0; i < actions.length; i++) {
if(actions[i].contains(data)) {
print(actions[i]);
// In your case show card or add in another list to show after
}
}
}

Flutter Unhandled Exception: NoSuchMethodError: The getter 'uid' was called on null

First of all, I would like to say I have seen all the previous posts on this error but none of them resolved my issue and that's why I am posting it.
Actually, I have understood the problem but unable to resolve it. So, the below dart file is my HomeScreen().
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:mukti/authentication/firestore_service.dart';
import 'package:mukti/schedule/task.dart';
import 'package:mukti/schedule/taskdata.dart';
import 'package:provider/provider.dart';
import 'add_class.dart';
import 'package:firebase_auth/firebase_auth.dart' as auth;
class HomeScreen extends StatefulWidget {
static final String routeName = 'homeScreen';
final auth.User firebaseUser;
HomeScreen({this.firebaseUser});
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final FirestoreService firestoreService = FirestoreService();
#override
Widget build(BuildContext context) {
print("HomeScreen");
print(widget.firebaseUser);
return Scaffold(
body: SafeArea(
child: SizedBox.expand(
child: Padding(
padding: const EdgeInsets.all(48.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width,
height: 450,
color: Colors.yellow[100],
child: generateTaskList(),
),
),
SizedBox(height: 45),
/* Add Class Button */
Center(
child: GestureDetector(
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) => AddClass(),
),
);
},
child: Container(
height: 75,
width: 75,
decoration: BoxDecoration(
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0, 4), //(x,y)
blurRadius: 1.0,
),
],
color: Color(0xFFF9A826),
),
child: Icon(
Icons.add,
size: 35,
color: Colors.white,
),
),
),
),
],
),
),
),
),
);
}
Widget generateTaskList() {
//print("Firebase User : ${widget.firebaseUser.uid}");
Provider.of<TaskData>(context, listen: false).loadTaskList(widget.firebaseUser);
print('List Generated');
var taskListLength = Provider.of<TaskData>(context, listen: false).getTaskListCount();
return Consumer<TaskData>(
builder: (context, taskData, child) => ListView.builder(
itemCount: taskData.taskList.length,
itemBuilder: (context, index) {
print("TaskList");
return Container(
padding: EdgeInsets.all(16.0),
decoration: new BoxDecoration (
borderRadius: BorderRadius.circular(10),
color: Color(0xFFF9A826),
),
child: ListTile(
title: Text(
taskData.taskList[index].description ?? 'default',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
subtitle: Text(
"${Util.getFormattedDate(taskData.taskList[index].scheduledDateTime)}" ?? 'default',
style: TextStyle(
color: Colors.white54,
),
),
),
);
}
)
);
}
}
class Util {
static String getFormattedDate(DateTime dateTime) {
return new DateFormat("EEE, MMM d, y").format(dateTime);
}
}
Initially, firebaseUser is not null, I have crossed checked it and it is printing the data in the app but when I add more entries from AddClass() and returns to HomeScreen() again, firebaseUser becomes null and no data is shown in the app anymore.
The below code is my AddClass() code:
import 'package:flutter/material.dart';
import 'package:mukti/authentication/authService.dart';
import 'package:mukti/authentication/firestore_service.dart';
import 'package:mukti/schedule/scheduled_date.dart';
import 'package:mukti/schedule/task.dart';
import 'package:mukti/ui_pages/main_screen/timepicker.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:firebase_auth/firebase_auth.dart' as auth;
import 'home_screen.dart';
class AddClass extends StatefulWidget {
static final String routeName = 'addClass';
#override
_AddClassState createState() => _AddClassState();
}
class _AddClassState extends State<AddClass> {
final FirestoreService firestoreService = FirestoreService();
#override
Widget build(BuildContext context) {
print("Add Class Screen");
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Color(0xFFFFFFE5),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
/* Meeting url TextField Widget */
/* Description TextField Widget */
/* Calender */
/* Add Class Button */
Expanded(
child: GestureDetector(
onTap: () async{
auth.User firebaseUser = await Provider.of<AuthService>(context, listen: false).getUser();
DateTime scheduledDateTime = Provider.of<ScheduledDate>(context, listen: false).scheduledDateTime;
print(scheduledDateTime);
print(firebaseUser);
final task = Task(
link: 'xyz',
isDone: false,
description: 'xyz',
scheduledDateTime: scheduledDateTime,
);
firestoreService.addTask(firebaseUser, task);
print('Task Added');
Navigator.popAndPushNamed(context,
HomeScreen.routeName,
arguments: firebaseUser,
);
},
child: Align(
alignment: FractionalOffset.bottomCenter,
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Color(0xFFF9A826),
),
child: Center(
child: Text(
'SCHEDULE CLASS',
style: Theme.of(context).textTheme.bodyText1.copyWith(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 16,
letterSpacing: 0.5,
),
)
)
),
),
),
),
],
),
),
);
}
}
Actually, I have removed unnecessary codes, so after adding one more class to the database, I return to HomeScreen but this time firebaseUser becomes null, although I am sending it in the argument of the routes HomeScreen is receiving null. This is my problem.
How can I resolve this..?
If anyone needs more information, feel free to ask me.
Thanks

How to change Text and Icon color depends on Background Image?

Anyone knows how to change icon and text color depending on the background color of the image or video?
The palette_generator package can help you find the most dominant color(s) in the image. You can use these color(s) to set the Text and Icon color.
Please check out the example code provided by the package author https://pub.dev/packages/palette_generator/example . The PaletteGenerator.fromImageProvider method can be used to get the color pallet from the image. You can use the following code from the example :
Future<void> _updatePaletteGenerator(Rect newRegion) async {
paletteGenerator = await PaletteGenerator.fromImageProvider(
widget.image,
size: widget.imageSize,
region: newRegion,
maximumColorCount: 20,
);
setState(() {});
}
....
Color dominantColor = paletteGenerator.dominantColor?.color;
....
Please see the entire working code below : (Add palette_generator: ^0.2.3 to your pubspec.yaml first)
import 'package:flutter/material.dart';
import 'package:palette_generator/palette_generator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Palette Generator',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future _updateColors;
final List<PaletteColor> _colors = [];
int _currentIndex;
final List<String> _images = [
'https://picsum.photos/id/491/200/300',
'https://picsum.photos/id/400/200/300',
'https://picsum.photos/id/281/200/300'
];
#override
void initState() {
super.initState();
_currentIndex = 0;
_updateColors = _updatePalettes();
}
Future<bool> _updatePalettes() async {
for (final String image in _images) {
final PaletteGenerator generator =
await PaletteGenerator.fromImageProvider(NetworkImage(image));
_colors.add(generator.dominantColor != null
? generator.dominantColor
: PaletteColor(Colors.blue, 2));
}
setState(() {});
return true;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Color Palette Generator Demo'),
elevation: 0,
backgroundColor: _colors.isNotEmpty
? _colors[_currentIndex].color
: Theme.of(context).primaryColor,
),
body: FutureBuilder<bool>(
future: _updateColors,
builder: (context, snapshot) {
if (snapshot.data == true)
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
height: 200,
color: _colors.isNotEmpty
? _colors[_currentIndex].color
: Colors.white,
child: PageView(
onPageChanged: (value) =>
setState(() => _currentIndex = value),
children: _images
.map((image) => Container(
padding: const EdgeInsets.all(16.0),
margin: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
image: DecorationImage(
image: NetworkImage(image),
fit: BoxFit.cover,
),
),
))
.toList(),
),
),
Expanded(
child: Container(
padding: const EdgeInsets.all(32.0),
width: double.infinity,
decoration: BoxDecoration(
color: _colors.isNotEmpty
? _colors[_currentIndex].color
: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"Color Palette",
style: TextStyle(
color: _colors.isNotEmpty
? _colors[_currentIndex].titleTextColor
: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30.0,
),
),
const SizedBox(height: 10.0),
Icon(
Icons.ac_unit,
size: 100,
color: _colors.isNotEmpty
? _colors[_currentIndex].bodyTextColor
: Colors.black,
)
],
),
),
),
],
);
return const Center(child: CircularProgressIndicator());
},
),
);
}
}