Unable to use the .map function in Flutter - list

So I am following along a book about Flutter App Development where I was tasked to implement a ToDoMenuItem class and create a list in it.
class TodoMenuItem {
final String title;
final Icon icon;
TodoMenuItem({this.title, this.icon});
List<TodoMenuItem> foodMenuList = [
TodoMenuItem(title: 'Fast Food', icon: Icon(Icons.fastfood)),
TodoMenuItem(title: 'Remind Me', icon: Icon(Icons.add_alarm)),
TodoMenuItem(title: 'Flight', icon: Icon(Icons.flight)),
TodoMenuItem(title: 'Music', icon: Icon(Icons.audiotrack)),
];
}
Then I was tasked to map it to a PopUpMenuButtonWidget using an itemBuilder. Here is the class I wrote for it.
class PopupMenuButtonWidget extends StatelessWidget
implements PreferredSizeWidget {
const PopupMenuButtonWidget({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Colors.lightGreen.shade100,
height: preferredSize.height,
width: double.infinity,
child: Center(
child: PopupMenuButton<TodoMenuItem>(
icon: Icon(Icons.view_list),
onSelected: ((valueSelected) {
print('valueSelected: ${valueSelected.title}');
}),
itemBuilder: (BuildContext context) {
return foodMenuList.map((TodoMenuItem todoMenuItem) {
return PopupMenuItem<TodoMenuItem>(
value: todoMenuItem,
child: Row(
children: <Widget>[
Icon(todoMenuItem.icon.icon),
Padding(
padding: EdgeInsets.all(8.0),
),
Text(todoMenuItem.title),
],
),
);
}).toList();
},
),
),
);
}
#override // implement preferredSize
Size get preferredSize => Size.fromHeight(75.0);
}
However, it returns an error at this line.
return foodMenuList.map((TodoMenuItem todoMenuItem) {
And the error says
Undefined name 'foodMenuList'.
Try correcting the name to one that is defined, or defining the name.
How can I 'map' the foodMenuList list to the widget?

Your foodMenuList is declared in todoMenuItem class, while you try to refer to it like it would be a part of PopupMenuButtonWidget (you are doing this.foodMenuList in context of PopupMenuButtonModget)
You could create instantiate an instance of TodoMenuList in PopupMenuButtonWidget and then use it.
final TodoMenuItem _todoMenu = TodoMenuItem();
Widget build(BuildContext context) {
...
// Someplace where you need to use the list
_todoMenu.foodMenuList
...
}

Related

How can i make a dynamic list in Flutter where user can add items through a textfield and delete the item again?

I want to have a textinputfield for the user and when he tips in something and clicks on a button the input should be shown in a list item. The user should also have the option to delete items of the list just like a in and todo app.
Here you can find my code:
Link to Code
So I decided to write this simple program just to freshen up my skills... You can directly copy paste this code and it should work just fine.
I have used the provider package here to make this a bit more professional, as you can't always rely on setState() to update your UI when tasks are added to your list. And also because you will probably be using the provider more often in the future.
I have added comments in the below code to make it easy to understand. However, do not hesitate to clear up any confusions in the comments :)
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo/list_provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider( // This initiates the provider.
create: (context) => TaskProvider(), // Initiating it here makes this provider data available everywhere in the application
child: MaterialApp(
title: 'Flutter Demo',
home: const MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Dynamic List'),
),
body: const HomePageBody(), // I pass a separate widget here just to make the code a bit cleaner
floatingActionButton: FloatingActionButton(
onPressed: () => showModalBottomSheet( // This calls a bottom Modal Sheet which pops up while pressing the floating action button
context: context, builder: (context) => const BottomSheet()),// The modal sheet displays the BottomSheet() Widget which I have defined down in this code.
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
// This is where the ListView will be shown
class HomePageBody extends StatelessWidget {
const HomePageBody({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
List<String> listOfTasks = Provider.of<TaskProvider>(context).getTasks; // This is where the list is being accessed from the Provider file.
return Container(
padding: const EdgeInsets.all(20),
child: ListView.builder(
itemCount: listOfTasks.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
listOfTasks[index],
),
);
},
),
);
}
}
// This is the BottomSheet Widget where I decided to take User Input from
class BottomSheet extends StatefulWidget {
const BottomSheet({Key? key}) : super(key: key);
#override
State<BottomSheet> createState() => _BottomSheetState();
}
class _BottomSheetState extends State<BottomSheet> {
String task = ''; // This variable holds the tasks user wants to add
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(
top: 20,
left: 20,
right: 20,
bottom: MediaQuery.of(context).viewInsets.bottom + 20, // viewInsets.bottom adds padding from the bottom to avoid keyboard overlapping textfield widget
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(// You can use TextField Widget as well
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
onChanged: (value) { // This saves the value in the TextField for every character the user types
task = value; // The value in the TextField is referred to by the 'value' variable
},
),
const SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () => saveTask(task),
child: const Text('Save Task'),
),
],
),
);
}
void saveTask(String task) {
Provider.of<TaskProvider>(context, listen: false).addTasks(task); //This is where I am calling the function to add a task to the list.
// The 'addTasks()' function is defined in the provider file which is just below
}
}
Here's the list_provider.dart file that I import in above code:
import 'package:flutter/foundation.dart';
class TaskProvider extends ChangeNotifier { // This is the class where your data exists
// and this is the only place where your data should be manipulated! I explain the reason below...
final List<String> _tasks = [];
List<String> get getTasks { // We use a getter to retrieve the list
return _tasks; // We do that in order to avoid modifications to this list from any outside sources.
}
void addTasks(task) {
_tasks.add(task); // This is simply how you add anything to a list
notifyListeners(); // This is why we use providers. This function notifies all the children widgets
// of the Widget where we initiated our provider (see the parent of MaterialApp Widget in the above code)
// This is why changes to data should be made within this class only as it extends ChangeNotifier,
// which provides us with notifyListeners() method. Which ultimately notifies the widgets that the data has been modified and its time to rebuild the widgets that rely on this data!
}
}
You can copy paste this code, just make sure to add the provider package in your pubspec.yaml file as shown below.

How to change "setState()" when using GetX in Flutter?

I have a login screen code like below that has a text button that changes the state of the Login button to Signup or reverse, and want to rewrite it to use GetX library. But I don't know how?
enum AuthMode { Signup, Login }
class AuthenticationScreen extends StatelessWidget {
const AuthenticationScreen({Key? key}) : super(key: key);
AuthMode _authMode = AuthMode.Login;
#override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = GlobalKey();
void _switchAuthMode() {
if (_authMode == AuthMode.Login) {
setState(() {
_authMode = AuthMode.Signup;
= });
_controller!.forward();
} else {
setState(() {
_authMode = AuthMode.Login;
});
_controller!.reverse();
}
}
return Scaffold(
body: Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 400),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
,
TextButton(
child: Text(
'${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} '),
onPressed: _switchAuthMode,
style: TextButton.styleFrom(
padding:
const EdgeInsets.symmetric(horizontal: 30.0, vertical: 4),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
textStyle: TextStyle(color: Theme.of(context).primaryColor),
),
],
),
),
),
);
}
}
I tried some changes like transferring Authmode to the auth_controller file that extends GetxController and add obs after AuthMode _authMode = AuthMode.Login; and try to use obx(()=>) inside the _switchAuthMode() but didn't work.
Try like this:
final authMode= Rx<AuthMode>(AuthMode.Login);
And then on your switchAuthMode method:
authMode.value = AuthMode.Signup; // without setState
And finally, wrap the Text widget with Obx:
Obx(()=> Text('${authMode.value == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} ')
And you can actually make your widget a StatelessWidget.

How do I reference to a List<> object that was created in a class?

I have 2 separate files in my Flutter application, main.dart and class1.dart
class1.dart is defined in my models/ folder
I am trying to access the List that I created from the SampleWidget class but I am unsure how to do this. IntelliSense wasn't able to find the List I had made from the instance object of SampleWidget.
What I'm trying to achieve is:
AssetImage(SampleWidget.listSampleWidget[0].foo)
class1.dart
class SampleWidget {
final String foo;
final int bar;
SampleWidget({this.foo, this.bar});
}
List<SampleWidget> listSampleWidget = [
SampleWidget(
foo: 'assets/001.png',
bar: 420,
),
];
main.dart is just the default boilerplate code when creating a new Flutter application,
main.dart
import 'package:flutter/material.dart';
import 'package:sandbox1/models/class1.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final extSampleClass = SampleWidget();
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
//AssetImage(<pass SampleWidget foo parameter from the List here>),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
How do I reference to the List from the class here? Is something like this even doable or is there a different approach?
AssetImage() cannot be used as a standalone widget. Using Image.asset() worked. I can call the List object directly without having to reference the class apparently.
So the code will look something like:
Image.asset(listSampleWidget[0].foo)
And I got the picture on my test device!

Manage items in a List with their ids

Let me explain, I have two List Views with Items. At the moment I don’t give an id to these items but I have a problem. In fact, when I remove an item from my favorites list, it doesn’t change the icon (favorite or not favorite) for the right item on the home_screen.
I want to get the place of the item in the menu screen so I can change the icon from the favorites list. I’m using the provider package.
And so I wonder if it wouldn’t be better to create an id for each item and store a List<int> and then create a List<Item> in my favorites list. Also, I can use this id to change the right icon.
But I don’t know how to use these ids to create a List and then change the right icon.
Illustrations of what I said :
Black heart = in favorite and White heart = not in favorite.
It is the wrong item which is deleting.
My code on Github ans some relevant parts of my code :
favModel.dart
class FavModel extends ChangeNotifier {
List<Item> favList = [];
List<bool> isInFav = [];
addInFavorite(title, description, index){
Item item = Item(title: title, description: description, );
favList.add(item);
isInFav[index] = true;
notifyListeners();
}
removeOfFavorite(int index, int index2){
favList.removeAt(index);
isInFav[index2] = false;
notifyListeners();
}
implement(){
isInFav.add(false);
}
}
favorite_screen.dart
class Favorite extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorite'),
),
body: Consumer<FavModel>(
builder: (context, favModel, child) {
return ListView.builder(
itemCount: favModel.favList.length,
itemBuilder: (context, index) {
return TextObject(favModel.favList[index].title,
favModel.favList[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
Icons.favorite,
color: Colors.red,
size: 32,
),
onTap: () {
favModel.removeOfFavorite(index, index);
}),
),
});
},
),
);
}
}
home_screen.dart
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: [
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) {
return Favorite();
},
),
),
),
],
),
body: Consumer<FavModel>(builder: (context, favModel, child) {
return ListView.builder(
shrinkWrap: false,
itemCount: itemData.length,
itemBuilder: (context, index) {
favModel.implement();
return TextObject(
itemData[index].title, itemData[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
favModel.isInFav.elementAt(index)
? Icons.favorite
: Icons.favorite_border,
color:
favModel.isInFav[index] ? Colors.red : null,
size: 32,
),
onTap: () {
favModel.isInFav[index]
? null
: Provider.of<FavModel>(context,
listen: false)
.addInFavorite(
itemData[index].title,
itemData[index].description,
index,
);
}),
);
});
}),
);
}
}
Where I want to get the index is in the favorite_screen.dart at this line favModel.removeOfFavorite(index, index);
I would suggest you to add bool isFavorite to your class Item and add an id for the class also. So you can avoid having two arrays.
And using the id will help you using some awesome methods like findWhere and removeWhere
EDIT
You can iterate the List using for
for(int i = 0;i<favList.length;i++){
if(favList[i].id == selectedItem.id){
favList[i].isSelected = true;
break;// break the loop no need to continue
}
}
notifyListeners()
Notice that now you have to pass Item instead of index

Flutter list of Text: How to fix the style of all list items

I am new to flutter and to the concept of Object orientation in general. I am building a list of Text to be used with a CupertinoPicker in flutter, I want to use the same style for all the list items but I don't want to keep repeating the lines and each time specifying the text style.
For example, see the list of car manufacturers below:
import 'package:flutter/material.dart';
TextStyle kStyle = TextStyle(color: Colors.white, fontWeight: FontWeight.w900);
List<Text> manufacturers = [
Text('Toyota', style: kStyle,),
Text('VolksWagen', style: kStyle,),
Text('Nissan', style: kStyle,),
Text('Renault', style: kStyle,),
Text('Mercedes', style: kStyle,),
Text('BMW', style: kStyle,)
];
You see the list items in manufacturers list can get so long with more cars, can I use a class to tell flutter that my style is fixed to kstyle for all the items without explicitly writing style: kstyle for every single line?
Basically We can use DefaultTextStyle widget
Final Result
CupertinoPicker Widget
Common Column Widget
1. The Problem is we need to use CupertinoPicker
which in the library, it is defined as
final Widget result = DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.pickerTextStyle,
child: Stack(
2. Solution : Override Theme
Therefore We are required to defined its style at the very beginning definition of our app
const TextStyle kStyle = TextStyle(
color: Colors.blue,
fontWeight: FontWeight.w900,
);
class FlutterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Cupertino Picker',
home: ListViewScreen(),
theme: ThemeData(
cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
textTheme: CupertinoTextThemeData(
pickerTextStyle: kStyle,
),
),
),
);
}
}
A. Full Working Code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(FlutterApp());
}
const TextStyle kStyle = TextStyle(
color: Colors.blue,
fontWeight: FontWeight.w900,
);
class FlutterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Cupertino Picker',
home: ListViewScreen(),
theme: ThemeData(
cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
textTheme: CupertinoTextThemeData(
pickerTextStyle: kStyle,
),
),
),
);
}
}
class ListViewScreen extends StatelessWidget {
final List<Text> manufacturers = [
Text('Toyota'),
Text('VolksWagen'),
Text('Nissan'),
Text('Renault'),
Text('Mercedes'),
Text('BMW')
];
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text("Select Car"),
),
child: Container(
height: 200,
child: CupertinoPicker(
itemExtent: 50,
onSelectedItemChanged: (int index) {
print(index);
},
children: manufacturers,
),
),
);
}
}
B. [Optional] Simple use of Default Text Style
List<Text> manufacturers = [
Text('Toyota'),
Text('VolksWagen'),
Text('Nissan'),
Text('Renault'),
Text('Mercedes'),
Text('BMW')
];
const TextStyle kStyle = TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
);
class CarList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: kStyle,
child: Column(
children: manufacturers,
),
);
}
}
You can create a new widget:
class MyTextWidget extends StatelessWidget {
final String text;
const MyTextWidget({Key key, this.text}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text(text,style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900),);
}
}
and use it in your list
List<Text> manufacturers = [
MyTextWidget('Toyota'),
MyTextWidget('VolksWagen'),
MyTextWidget('Nissan'),
MyTextWidget('Renault'),
MyTextWidget('Mercedes'),
MyTextWidget('BMW')
];
If you want to change the font in all the application, you must change it from MaterialApp like this:
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
//Use the appropriate TextStyle
),
),);
}
You can create one method for all Text widgets:
Text styledText(String text) => Text(text, style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900));
and use it in your list:
List<Text> manufacturers = [
styledText('Toyota'),
styledText('VolksWagen'),
styledText('Nissan'),
styledText('Renault'),
styledText('Mercedes'),
styledText('BMW')
];
You can also create a list of strings
List<String> manufacturers = [
'Toyota',
'VolksWagen',
'Nissan',
'Renault',
'Mercedes',
'BMW',
];
And use tis method when you iterate through your list.
Or you can create a class instead of the method:
class CustomStyledText extends StatelessWidget {
final String text;
const CustomStyledText(this.text, {Key key}) : super(key: key);
TextStyle get _style => TextStyle(color: Colors.white, fontWeight: FontWeight.w900);
#override
Widget build(BuildContext context) => Text(text, style: _style);
}
You can create an extension on the Text widget and use that:
Create an extension:
// extension
extension on Text {
// method to apply style
applyStyle(TextStyle textStyle) {
return Text(
this.data,
style: textStyle,
);
}
}
Use the extension method on the Text widget:
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...List.generate(
manufacturers.length,
// call the applyStyle method on the Text widget
(index) => manufacturers[index].applyStyle(kStyle),
).toList(),
],
),
);