Flutter: Card() / Firebase - (Beginner problem) - flutter

I am new in Flutter. I have a problem with a small project. I collect data from a Firebase DB and adding it into a listTile. I am trying to add 2 static ListTile but they are added to the homescreen for every loop. I can't get a out of the loop - Any one there are willing to help.
The "Datablade" and "Vejledning" listtile are added for every loop
'''
import 'package:flutter/material.dart';
import 'package:flutter_app/services/auth.dart';
import 'package:flutter_app/services/database.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
//import 'package:flutter_app/screens/home/brew_list.dart';
import 'package:flutter_app/models/brew.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
return StreamProvider<List<Brew>>.value(
value: DatabaseService().filer,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Arbejdsmiljø'),
backgroundColor: Colors.orange[400],
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('Log ud'),
onPressed: () async {
await _auth.signOut();
},
),
],
),
body:
ListPage(),
),
);
//ListPage(),
}
}
class ListPage extends StatefulWidget {
#override
_ListPageState createState() => _ListPageState();
}
class _ListPageState extends State<ListPage> {
Future _data;
Future getPosts() async{
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection('filer').getDocuments();
return qn.documents;
}
navigateToDetail(DocumentSnapshot post) {
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(post: post,)));
}
void initState() {
super.initState();
_data = getPosts();
}
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: _data,
builder: (_, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: Text('Loading'),
);
} else {
return ListView.builder(
//return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index){
return Card(
child: Column(
children: <Widget> [
ListTile(
leading: Icon(Icons.star, color: Colors.orange, size: 26.0),
onTap: () => navigateToDetail(snapshot.data[index]),
title: Text('Datablade'),
trailing: Icon(Icons.keyboard_arrow_right),
),
Divider(color: Colors.orange,indent: 16.0),
ListTile(
title: new Center(child: new Text("Vejledninger",
style: new TextStyle(
color: Colors.orange[400],
fontWeight: FontWeight.w500, fontSize: 25.0),)),
),
ListTile(
onTap: () => navigateToDetail(snapshot.data[index]),
title: Text(snapshot.data[index].data["name"]),
leading: CircleAvatar(
backgroundColor: Colors.orange[400],
foregroundColor: Colors.white,
child: Text(snapshot.data[index].data["name"][0])
)
)
],
),
);
//return ListTile(
//title: Text(snapshot.data[index].data["name"]),
//onTap: () => navigateToDetail(snapshot.data[index]),
//);
});
}
}),
);
}
}
class DetailPage extends StatefulWidget {
final DocumentSnapshot post;
DetailPage ({this.post});
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.post.data["name"]),
),
body: Container(
child: Card(
child: ListTile(
title: Text(widget.post.data["name"]),
subtitle: Text(widget.post.data['beskrivelse']),
),
),
),
);
}
}
'''

Related

Refresh the page data when you go to this page in the flutter

I'm trying to write a small application in which I collect data through api. I take the data, everything works. I decided to make a navigation bar to switch between pages. But when I try on the pages they are empty. In order for the data to be updated on the page, I need to click "Hot reload". I will be grateful for your help.
My main.dart:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/dataArea_list/JsonDataArea.dart';
import 'package:flutter_app_seals/model/object_list/JsonObject.dart';
import 'package:flutter_app_seals/model/seals_list/JsonSeals.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Журнал пломби'),
),
// body: Seals(),
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Seals List"),
trailing: Icon(Icons.arrow_back),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Seals()),
);
}
)
],
),
),
);
}
}
class Seals extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home:JsonParseSeals(),
);
}
}
My modul Seals:
import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/seals_list/SealsListGet.dart';
import 'package:flutter_app_seals/model/seals_list/ServicesSeals.dart';
class JsonParseSeals extends StatefulWidget {
//
JsonParseSeals() : super();
#override
_JsonParseSealsState createState() => _JsonParseSealsState();
}
class _JsonParseSealsState extends State <StatefulWidget> {
//
List<SealList> _seals;
bool _loading;
#override
void initState(){
super.initState();
_loading = true;
Services.getSeals().then((seals) {
_seals =seals;
_loading = false;
}
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Список пломби'),
),
body: ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(40),
itemCount: null == _seals ? 0 :_seals.length,
itemBuilder: (_,index) => Card(
color: Colors.red[300],
margin: EdgeInsets.symmetric(vertical: 7),
child:ListTile(
title: Text(_seals[index].sealNumber,
style: TextStyle(fontSize: 30),
),
subtitle: Text(
"${_seals[index].used}" ),
leading: Icon(Icons.local_activity,
size: 40,
color: Colors.black87,
),
),
),
),
);
}
}
My code :
Code after change:
Try to wrap your screen with data in FutureBuilder (you can read more about this widget here):
class _JsonParseSealsState extends State <StatefulWidget> {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<SealList>>(
future: Services.getSeals(),
builder: (context, snapshot) {
// Data is loading, you should show progress indicator to a user
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
// Data is loaded, handle it
return ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(40),
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
final item = snapshot.data[index];
return Card(
color: Colors.red[300],
margin: EdgeInsets.symmetric(vertical: 7),
child: ListTile(
title: Text(
item.sealNumber,
style: TextStyle(fontSize: 30),
),
subtitle: Text("${item.used}"),
leading: Icon(
Icons.local_activity,
size: 40,
color: Colors.black87,
),
),
);
},
),
}
);
}
}

Issues with ToDo list

I have several questions:
How can you create a todo list with deletable tiles, usable checkboxes and how can u save data, that a user put in?
I have currently found a tutorial with stateless tiles where you cant use the tickboxes or delete the tiles...
In my case the whole stuff gets wiped and the toDO list is trash...
Thank you for your help ^^
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: ToDo()));
class ToDo extends StatefulWidget {
#override
_ToDoState createState() => _ToDoState();
}
class _ToDoState extends State<ToDo> {
List<String> products = ['Tomate', 'Käse', 'Lauch', 'Paprika' ,'Wein'];
void addItem(String item) {
setState(() {
products.add(item);
});
Navigator.of(context).pop();
}
void newEntry() {
showDialog<AlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: TextField(
onSubmitted: addItem,
),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("To-Do-App"),
backgroundColor: Color.fromRGBO(35, 152, 185, 100),
),
body:
ListView.builder(
itemCount: products.length,
itemBuilder: (context, i) {
return ToDoItem( products[i] );
},
),
floatingActionButton: FloatingActionButton(
onPressed: newEntry,
child: Icon(Icons.add),
),
);
}
}
class ToDoItem extends StatelessWidget {
final String title;
const ToDoItem(this.title);
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 22),
child: ListTile(
contentPadding: EdgeInsets.symmetric(vertical: 8.0),
leading: Checkbox(
value: false,
),
title: Text(
title,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.w600,
color: Colors.black54),
),
trailing: Icon(Icons.delete_outline),
),
);
}
}

Flutter: Display all users from flutterstore excluding the currently logged in user

I am creating a chat ui for my flutter app. Right now I have managed to display all the users from firestore. But I want to show them excluding the current user logged in to the app.
Here is my code:
class Chats extends StatefulWidget {
final String chatUserId;
Chats({this.chatUserId});
#override
_ChatState createState() => _ChatState(
chatUserId:this.chatUserId,
);
}
class _ChatState extends State<Chats> {
TextEditingController chatController = TextEditingController();
Future<QuerySnapshot> chatUsers;
final String chatUserId;
_ChatState({this.chatUserId});
#override
Widget build(BuildContext context) {
setState(() {
chatUsers = usersRef.getDocuments();
});
return Scaffold(
backgroundColor: Colors.white,
appBar: header(context,titleText: 'GupShup'),
body:FutureBuilder(
future: chatUsers,
builder: (context,snapshot){
if(snapshot.hasData){
List<ChatResult> results = [];
snapshot.data.documents.forEach((doc){
User user = User.fromDocument(doc);
ChatResult result = ChatResult(user);
results.add(result);
});
return ListView(
children: results,
);
}
return circularProgress();
}
),
);
}
}
class ChatResult extends StatelessWidget {
final User user;
ChatResult(this.user);
#override
Widget build(BuildContext context) {
return Container(
color:Colors.white,
child: Column(
children: <Widget>[
GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context)=> ChatScreen(
username: user.displayName,
uuid: Uuid().v4().toString()))),
child:
ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
),
title: Text(user.displayName,style: TextStyle(fontWeight: FontWeight.bold),),
subtitle: Text('message'),
),
),
Divider(
height: 2.0,
color: Colors.black,
),
],
),
);
}
}
Here's the result
Now, currently Nilima Bordoloi has been logged in. How to hide this user?
Also, is there any way to look this page more beautiful like whatsapp or messenger?
Any help would be appreciable.
Thank You...
class Chats extends StatefulWidget {
final String chatUserId;
Chats({this.chatUserId});
#override
_ChatState createState() => _ChatState(
chatUserId:this.chatUserId,
);
}
class _ChatState extends State<Chats> {
TextEditingController chatController = TextEditingController();
Future<QuerySnapshot> chatUsers;
final String chatUserId;
_ChatState({this.chatUserId});
#override
Widget build(BuildContext context) {
setState(() {
chatUsers = usersRef.getDocuments();
});
return Scaffold(
backgroundColor: Colors.white,
appBar: header(context,titleText: 'GupShup'),
body:FutureBuilder(
future: chatUsers,
builder: (context,snapshot){
if(snapshot.hasData){
List<ChatResult> results = [];
snapshot.data.documents.forEach((doc){
User user = User.fromDocument(doc);
//check here if the uid of user is != chatUserId
//if it is not,(meaning it is not the currently logged in user) add
//him to results
if(user.uid != chatUserId.uid){
ChatResult result = ChatResult(user);
results.add(result);
}
});
return ListView(
children: results,
);
}
return circularProgress();
}
),
);
}
}
class ChatResult extends StatelessWidget {
final User user;
ChatResult(this.user);
#override
Widget build(BuildContext context) {
return Container(
color:Colors.white,
child: Column(
children: <Widget>[
GestureDetector(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context)=> ChatScreen(
username: user.displayName,
uuid: Uuid().v4().toString()))),
child:
ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
),
title: Text(user.displayName,style: TextStyle(fontWeight: FontWeight.bold),),
subtitle: Text('message'),
),
),
Divider(
height: 2.0,
color: Colors.black,
),
],
),
);
}
}

FutureBuilder not triggered after Navigator.pop

In my app, the FutureBuilder works fine when I use BottomNavigationBarItem (cf Home widget).
However, when I user Navigator.push and Navigator.pop, the FutureBuilder is not triggered.
I can't understand why, any help would be highly appreciated.
Bellow my code.
Home widget
import 'package:com.pro.cocotal.online/models/product.dart';
import 'package:com.pro.cocotal.online/models/user.dart';
import 'package:com.pro.cocotal.online/screens/home/products/productListScreen.dart';
import 'package:com.pro.cocotal.online/screens/home/shopSettings/shopSettings.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
final User user;
final List<Product> products;
Home(this.user, this.products);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _selectedIndex = 0;
List<Widget> _widgetOptions;
#override
void initState(){
_widgetOptions = <Widget>[
ProductListScreen(widget.user, widget.products),
ShopSettings(widget.user),
];
}
//navigue dans les menus
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: Scaffold(
body:_widgetOptions.elementAt(_selectedIndex),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
title: Text(''),
icon: Icon(Icons.home, color: Colors.blueAccent, size: 35),
),
BottomNavigationBarItem(
title: Text(''),
icon: Icon(Icons.settings, color: Colors.blueAccent, size: 35)
)
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
),
)
);
}
}
ProductListScreen class
import 'package:com.pro.cocotal.online/models/product.dart';
import 'package:com.pro.cocotal.online/models/user.dart';
import 'package:com.pro.cocotal.online/screens/home/products/addProductScreen.dart';
import 'package:com.pro.cocotal.online/screens/home/products/productScreen.dart';
import 'package:com.pro.cocotal.online/services/productService.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class ProductListScreen extends StatefulWidget {
final List<Product> products;
final User user;
ProductListScreen(this.user, this.products);
#override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<ProductListScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tienda " + widget.user.storeName),
elevation: 0,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
backgroundColor: Colors.blue,
expandedHeight: 130,
flexibleSpace: FlexibleSpaceBar(
background: Image.network(
"https://cocotal.online/wp-content/uploads/revslider/cropped-slider-41.jpg",
fit: BoxFit.cover,
),
),
),
FutureBuilder(
future: ProductService().getProducts(widget.user),
builder: (context, productSnaps){
List<Product> products = productSnaps.data;
if (productSnaps.connectionState != ConnectionState.done) {
return SliverFixedExtentList(
itemExtent: 1,
delegate: SliverChildBuilderDelegate(
(context, i) {
return SpinKitRotatingCircle(
color: Colors.white,
size: 50.0,
);
},
childCount: 1,
),
);
}
if (productSnaps.hasData == null) {
return SliverFixedExtentList(
itemExtent: 0,
delegate: SliverChildBuilderDelegate(
(context, i) {
return ListTile(
title: Text("null"),
trailing: Icon(Icons.delete),
onTap: () {
},
);
},
childCount: 1,
),
);
}
return SliverFixedExtentList(
itemExtent: 50,
delegate: SliverChildBuilderDelegate(
(context, i) {
return ListTile(
title: Text(products[i].name),
trailing: Icon(Icons.delete),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ProductScreen(products[i])));
},
);
},
childCount: products.length,
),
);
},
),
],
),
),
RaisedButton.icon(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => AddProduct()));
},
icon: Icon(Icons.add_circle),
label: Text('Add a product')
),
],
)
);
}
}
ProductScreen class
import 'package:com.pro.cocotal.online/models/product.dart';
import 'package:flutter/material.dart';
class ProductScreen extends StatefulWidget {
final Product product;
const ProductScreen(this.product);
#override
_ProductScreenState createState() => _ProductScreenState();
}
class _ProductScreenState extends State<ProductScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.product.name),
leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: ()async{
Navigator.pop(context);
}),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
children: <Widget>[
Text("Nom : " + widget.product.name),
],
),
Row(
children: <Widget>[
Text("Description : " + widget.product.description),
],
),
Row(
children: <Widget>[
Text("Prix : " + widget.product.price),
],
),
],
),
);
}
}

Can someone check my Dart code and tell me where I'm making mistake in returning data from my screen as a ListView

I am stuck here for the past 20 days in returning data in my app from the other screen. I'm new to programming and need help. I've been searching through all the internet to find an answer related to my query but nothing is helping though. I ask my fellow SO guys to please help.
You can look at the entire code which I've made open here.
My code:
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
final newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {
return ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index){
return Container(
child: Text('item: $newList'),
);
},
);
});
},
)
],
),
);
}
}
The screen where Navigator.pop() is used:
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text(nameOfSite[index]),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}
Here is the SecondPage and FavoriteList that I made
import 'package:flutter/material.dart';
import 'package:aioapp2/lists.dart';
Set<int> favorites = {};
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: <Widget>[
_getFavoriteList(),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: FloatingActionButton(
child: Icon(
Icons.edit,
color: Colors.blue,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditFavorites(),
),
).then((updatedFavorites) {
if (updatedFavorites != null)
setState(() {
favorites = updatedFavorites;
});
});
},
),
),
)
],
);
}
Widget _getFavoriteList() {
if (favorites?.isNotEmpty == true)
return _FavoriteList();
else
return _EmptyFavoriteList();
}
}
class _EmptyFavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Add Your Favorite Sites Here!❤',
style: TextStyle(color: Colors.white),
),
Icon(
Icons.favorite,
size: 150,
color: Colors.blue[100],
),
],
),
),
),
),
],
);
}
}
class _FavoriteList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: favorites.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[favorites.elementAt(index)]),
);
},
);
}
}
//Its FavoriteList Page. I changed the name
class EditFavorites extends StatefulWidget {
#override
_EditFavoritesState createState() => _EditFavoritesState();
}
class _EditFavoritesState extends State<EditFavorites> {
final _editableFavorites = <int>{};
#override
void initState() {
_editableFavorites.addAll(favorites);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red,
actions: <Widget>[
IconButton(
icon: Icon(Icons.done),
onPressed: () {
Navigator.pop<Set>(context, _editableFavorites);
},
)
],
),
//backgroundColor: Colors.indigo,
body: SafeArea(
child: ListView.builder(
itemCount: nameOfSite.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('lib/images/${images[index]}'),
),
title: Text(nameOfSite[index]),
trailing: IconButton(
icon: _editableFavorites.contains(index)
? Icon(
Icons.favorite,
color: Colors.red,
)
: Icon(
Icons.favorite_border,
color: Colors.grey,
),
onPressed: () {
setState(() {
if (_editableFavorites.contains(index))
_editableFavorites.remove(index);
else
_editableFavorites.add(index);
});
},
),
);
},
),
),
);
}
}
Just replace secondtab.dart with this code.
You can copy paste run full code below
You have to move out return ListView to the same layer with FloatingActionButton
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SecondPage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
Set newList = {};
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(30),
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
ListView.builder(
itemCount: newList.length,
itemBuilder: (context, index) {
return Container(
child: Text('item: ${newList.elementAt(index)}'),
);
},
),
FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
onPressed: () async {
newList = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavoriteList(),
),
);
setState(() {});
},
)
],
),
);
}
}
final Set saved = Set();
class FavoriteList extends StatefulWidget {
#override
_FavoriteListState createState() => _FavoriteListState();
}
class _FavoriteListState extends State<FavoriteList> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add to Favorites!'),
centerTitle: true,
backgroundColor: Colors.red),
body: SafeArea(
child: ListView.builder(
itemCount: 53,
itemBuilder: (context, index) {
return CheckboxListTile(
activeColor: Colors.red,
checkColor: Colors.white,
value: saved.contains(index),
onChanged: (val) {
setState(() {
// isChecked = val; // changed
// if(val == true){ // changed
// __saved.add(context); // changed
// } else{ // changed
// __saved.remove(context); // changed
// } // changed
if (val == true) {
saved.add(index);
} else {
saved.remove(index);
}
});
},
title: Row(
children: <Widget>[
//Image.asset('lib/images/${images[index]}'),
SizedBox(
width: 10,
),
Text('nameOfSite[index]'),
],
),
);
},
),
),
floatingActionButton: FloatingActionButton(
foregroundColor: Colors.red,
child: Icon(Icons.check),
onPressed: () {
Navigator.pop<Set>(context, saved);
},
),
);
}
}