How do i customize flappy_search_bar in flutter - flutter

whenever i enter a value in search bar i want to match it from the available list, for example if this is my list
List fooList = ['one', 'two', 'three', 'four', 'five']; and i enter e in search bar it should list those items which contains e in it. How can i do that, anybody please help.
class _HomeState extends State<HeaderWithSearchBox1> {
final SearchBarController<Post> _searchBarController = SearchBarController();
Future<List<Post>> _getALlPosts(String text) async {
List<Post> posts = [];
var random = new Random();
for (int i = 0; i < 10; i++) {
posts
.add(Post("$text $i", "body random number : ${random.nextInt(100)}"));
}
return posts;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SearchBar<Post>(
minimumChars: 1,
searchBarPadding: EdgeInsets.symmetric(horizontal: 10),
headerPadding: EdgeInsets.symmetric(horizontal: 10),
listPadding: EdgeInsets.symmetric(horizontal: 10),
onSearch: _getALlPosts,
searchBarController: _searchBarController,
placeHolder: Center(
child: Text(
"PlaceHolder",
style: TextStyle(fontSize: 30),
)),
cancellationWidget: Text("Cancel"),
emptyWidget: Text("empty"),
onCancelled: () {
print("Cancelled triggered");
},
mainAxisSpacing: 10,
onItemFound: (Post post, int index) {
return Container(
color: Colors.lightBlue,
child: ListTile(
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.body),
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Detail()));
},
),
);
},
),
),
);
}
}
class Detail extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Center(child: Text("Detail", style: TextStyle(fontSize: 30),)),
),
);
}
}

You can copy paste run full code below
You filter fooList with where and use contains
code snippet
Future<List<Post>> _getALlPosts(String text) async {
List<Post> posts = fooList
.where((element) =>
element.title.contains(text) || element.body.contains(text))
.toList();
return posts;
}
working demo
full code
import 'dart:math';
import 'package:flappy_search_bar/flappy_search_bar.dart';
import 'package:flappy_search_bar/scaled_tile.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Post {
final String title;
final String body;
Post(this.title, this.body);
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final SearchBarController<Post> _searchBarController = SearchBarController();
bool isReplay = false;
List<Post> fooList = [
Post('one', '1'),
Post('two', '2'),
Post('three', '3'),
Post('four', '4'),
Post('five', '5')
];
Future<List<Post>> _getALlPosts(String text) async {
List<Post> posts = fooList
.where((element) =>
element.title.contains(text) || element.body.contains(text))
.toList();
return posts;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SearchBar<Post>(
minimumChars: 1,
searchBarPadding: EdgeInsets.symmetric(horizontal: 10),
headerPadding: EdgeInsets.symmetric(horizontal: 10),
listPadding: EdgeInsets.symmetric(horizontal: 10),
onSearch: _getALlPosts,
searchBarController: _searchBarController,
placeHolder: Center(
child: Text(
"PlaceHolder",
style: TextStyle(fontSize: 30),
)),
cancellationWidget: Text("Cancel"),
emptyWidget: Text("empty"),
onCancelled: () {
print("Cancelled triggered");
},
mainAxisSpacing: 10,
onItemFound: (Post post, int index) {
return Container(
color: Colors.lightBlue,
child: ListTile(
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.body),
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Detail()));
},
),
);
},
),
),
);
}
}
class Detail extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
Text("Detail"),
],
),
),
);
}
}

Related

When i refresh the page i couldn't get firestore realtime data with Flutter

I'm developing flutter web project. When I log in successfully at the first launch of the application, I can get the data in the firestore. However, when I refresh the web page or add new data after the data is received, the updated data does not appear on the screen, it is waiting in an if condition. Is this because Flutter can't draw the refreshed screen? What way can I follow?
**import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:moyes_home_project/view/candidate_addform.dart';
import 'package:moyes_home_project/view/constants.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'candidate_updateform.dart';
enum Menu { itemOne, itemTwo, itemThree }
class CandidatePool extends StatefulWidget {
const CandidatePool({Key? key}) : super(key: key);
#override
State<CandidatePool> createState() => _CandidatePoolState();
}
final Stream<QuerySnapshot> _usersStream =
FirebaseFirestore.instance.collection('candidateinfo').snapshots();
class _CandidatePoolState extends State<CandidatePool> {
#override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(defaultPadding),
child: Column(
// ignore: prefer_const_literals_to_create_immutables
children: [
const MyFiles(),
const Candidatepooltittle(),
const SizedBox(height: defaultPadding),
],
)));
}
}
class Candidatepooltittle extends StatefulWidget {
const Candidatepooltittle({Key? key}) : super(key: key);
#override
State<Candidatepooltittle> createState() => _CandidatepooltittleState();
}
class _CandidatepooltittleState extends State<Candidatepooltittle> {
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(defaultPadding),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const CircularProgressIndicator();
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
return SizedBox(
width: double.infinity,
child: DataTable(
columnSpacing: defaultPadding,
columns: const [
DataColumn(
label: Text('test1'),
),
DataColumn(
label: Text('test2'),
),
DataColumn(
label: Text('test3'),
),
DataColumn(
label: Text('test4'),
),
DataColumn(
label: Text('test5'),
),
DataColumn(label: Text(''))
],
rows: snapshot.data!.docs
.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return DataRow(cells: [
DataCell(
Text(data['test5']),
),
DataCell(Text(data['test4']!)),
DataCell(Text(data['test3']!)),
DataCell(Text(data['test2']!)),
const DataCell(Text('test1')),
DataCell(Row(children: [
PopupMenuButton<Menu>(
padding: const EdgeInsets.only(
right: 2, left: 1, top: 2),
onSelected: (value) async {
if (value == Menu.itemOne) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => View(
url: data['fileUrl'],
)));
} else if (value == Menu.itemTwo) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
Candidateupdateform(document,
candidate: document)));
} else if (value == Menu.itemThree) {
final docdelete = FirebaseFirestore
.instance
.collection('candidateinfo')
.doc(document.id);
docdelete.delete();
}
},
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<Menu>>[
const PopupMenuItem<Menu>(
value: Menu.itemOne,
child: Text('test'),
),
const PopupMenuItem<Menu>(
value: Menu.itemTwo,
child: Text('test'),
),
const PopupMenuItem<Menu>(
value: Menu.itemThree,
child: Text('test'),
)
])
]))
]);
}).toList()));
})
]));
}
}
class View extends StatelessWidget {
PdfViewerController? _pdfViewerController;
final url;
View({Key? key, this.url}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('test'),
),
body: SfPdfViewer.network(
url,
controller: _pdfViewerController,
),
);
}
}
class MyFiles extends StatelessWidget {
const MyFiles({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final Size _size = MediaQuery.of(context).size;
return Column(children: [
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
ElevatedButton.icon(
style: TextButton.styleFrom(
// ignore: prefer_const_constructors
padding: EdgeInsets.symmetric(
horizontal: defaultPadding * 1.5,
),
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Candidateaddform()));
},
icon: const Icon(Icons.add),
label: const Text("test"),
),
])
]);
}
}**

Additional filters in Flutter

I am writing an application on Flutter. I was able to make one filter with multiple selections.
But I want to have additional filters.
I used Multi-Select, but in the case of multiple filters, I don't know how to apply it
With what help can I implement this?
import 'package:flutter/material.dart';
class MainPage extends StatelessWidget {
#override
Widget build(context) => Scaffold(
appBar: AppBar(title: Text("f"),
backgroundColor: Colors.black),
drawer: MediaQuery.of(context).size.width < 500 ? Drawer(
child: HomePage(),
) : null,
body: SafeArea(
child:Center(
child: MediaQuery.of(context).size.width < 500 ? Content() :
Row(
children: [
Container(
width: 200.0,
child: HomePage()
),
Container(
width: MediaQuery.of(context).size.width-200.0,
child: Content()
)
]
)
)
)
);
}
List devices_list = ["First device", "Second device", "Third device", "Fourth device", "Fifth device", "Sixth device", "Seventh device", "Eighth device", "Ninth device"];
class Content extends StatelessWidget{
#override
Widget build(context) =>
Scaffold(
backgroundColor: Colors.white,
body: LayoutBuilder(
builder: (context, constraints){
return AnimatedContainer(
duration: Duration(milliseconds: 500),
color: Colors.white,
child: Center(
child: Container(
constraints: BoxConstraints(
maxWidth: 800,),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0),),
child: ListView.builder(
itemCount: devices_list.length,
itemBuilder: (BuildContext context, int index) {
return SizedBox (
height: 60,
key: Key(devices_list[index]),
child: Card(
shape: const RoundedRectangleBorder(
side: BorderSide(color: Colors.black,width: 3),
borderRadius: BorderRadius.all(Radius.circular(15))),
child: TextButton(
onPressed: (){},
child: ListTile(title: Text(devices_list[index]))),
)
);
}
))));
}));
}
class MultiSelect extends StatefulWidget {
final List<String> items;
const MultiSelect({Key? key, required this.items}) : super(key: key);
#override
State<StatefulWidget> createState() => _MultiSelectState();
}
class _MultiSelectState extends State<MultiSelect> {
// this variable holds the selected items
final List<String> _selectedItems = [];
// This function is triggered when a checkbox is checked or unchecked
void _itemChange(String itemValue, bool isSelected) {
setState(() {
if (isSelected) {
_selectedItems.add(itemValue);
} else {
_selectedItems.remove(itemValue);
}
});
}
// this function is called when the Cancel button is pressed
void _cancel() {
Navigator.pop(context);
}
// this function is called when the Submit button is tapped
void _submit() {
Navigator.pop(context, _selectedItems);
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Select Manufactures'),
content: SingleChildScrollView(
child: ListBody(
children: widget.items
.map((item) => CheckboxListTile(
value: _selectedItems.contains(item),
title: Text(item),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (isChecked) => _itemChange(item, isChecked!),
))
.toList(),
),
),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: _cancel,
),
ElevatedButton(
child: const Text('Submit'),
onPressed: _submit,
),
],
);
}
}
// Implement a multi select on the Home screen
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> _selectedItemsManufactures = [];
void _showMultiSelectManufactures() async {
// a list of selectable items
// these items can be hard-coded or dynamically fetched from a database/API
final List<String> _items = [
'Apple',
'Samsung',
'Xiaomi',
'Nokia',
'Huawei',
'Alcatel'
];
final List<String>? results = await showDialog(
context: context,
builder: (BuildContext context) {
return MultiSelect(items: _items);
},
);
// Update UI
if (results != null) {setState(() {_selectedItemsManufactures = results;});}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// use this button to open the multi-select dialog
ElevatedButton(
child: const Text('Manufactures'),
onPressed: _showMultiSelectManufactures,
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.black)
),
),
const Divider(
height: 5,
color: Colors.white,
),
// display selected items
Wrap(
children: _selectedItemsManufactures
.map((e) => Chip(
label: Text(e),
))
.toList(),
)
],
),
),
);
}
}
Addition. Addition. I would like changes in the Menu class to be reflected in the class MainPage.
class DevicesPage extends StatelessWidget {
#override
Widget build(context) => Scaffold(
appBar: AppBar(title: Text("IT"),
backgroundColor: Colors.black),
drawer: MediaQuery.of(context).size.width < 500 ? Drawer(
child: Menu(),
) : null,
body: SafeArea(
child:Center(
child: MediaQuery.of(context).size.width < 500 ? MainPage() :
Row(
children: [
Container(
width: 200.0,
child: Menu()
),
Container(
width: MediaQuery.of(context).size.width-200.0,
child: MainPage()
)
]
)
)
)
);
}
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
Map<String, List<String>?> filters = {};
List<Phone> filteredPhones = phoneList;
#override
Widget build(BuildContext context) {
return Scaffold(
body: filteredPhones.isEmpty
? const Center(child: Text('No product', style: TextStyle(fontSize: 16),))
: ListView.builder(
itemCount: filteredPhones.length,
itemBuilder: (_, index) {
final currentPhone = filteredPhones[index];
return ListTile(
title: Text(currentPhone.name),
subtitle: Text('${currentPhone.brand}-${currentPhone.color}'),
trailing: Text('${currentPhone.operation_system}'),
);
}
),
);
}
}
class Menu extends StatefulWidget {
const Menu({Key? key}) : super(key: key);
#override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
Map<String, List<String>?> filters = {};
List<Phone> filteredPhones = phoneList;
void _filter() {
setState(() {
filteredPhones = phoneList;
filters.forEach((key, value) {
if((value ?? []).isNotEmpty) {
filteredPhones = filteredPhones.where((phone) {
switch(key) {
case 'brand':
return value!.contains(phone.brand);
case 'color':
return value!.contains(phone.color);
case 'operation_system':
return value!.contains(phone.operation_system);
return true;
default:
return false;
}
}).toList();
}
});
filters.clear();
Navigator.of(context).pop();
});
}
void _handleCheckFilter(bool checked, String key, String value) {
final currentFilters = filters[key] ?? [];
if(checked) {
currentFilters.add(value);
} else {
currentFilters.remove(value);
}
filters[key] = currentFilters;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('phones List'),
actions: [
IconButton(
icon: const Icon(Icons.filter_alt),
onPressed: () {
showDialog<Filter>(context: context, builder: (_) {
return SimpleDialog(
title: const Text('Filters',textAlign: TextAlign.center,),
contentPadding: const EdgeInsets.all(16),
children: [
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('Select a brand'),
...brands.map((el) =>
CustomCheckboxTile(
label: el,
onChange: (check) => _handleCheckFilter(check, 'brand', el),
),
).toList(),
const Text('Select a operation_system'),
...operation_system.map((el) =>
CustomCheckboxTile(
label: el,
onChange: (check) => _handleCheckFilter(check, 'operation_system', el),
)
).toList(),
const Text('Select a colors'),
...colors.map((el) =>
CustomCheckboxTile(
label: el,
onChange: (check) => _handleCheckFilter(check, 'color', el),
),
).toList(),
const SizedBox(height: 24,),
ElevatedButton(onPressed: _filter, child: const Text('APPLY')),
],
),
],
);
});
},
),
],
),
body: filteredPhones.isEmpty
? const Center(child: Text('No product', style: TextStyle(fontSize: 16),))
: ListView.builder(
itemCount: filteredPhones.length,
itemBuilder: (_, index) {
final currentPhone = filteredPhones[index];
return ListTile(
title: Text(currentPhone.name),
subtitle: Text('${currentPhone.brand}-${currentPhone.color}'),
trailing: Text('${currentPhone.operation_system}'),
);
}
),
);
}
}
enter image description here
Well... you have many options. One way is to store all filters selected in a Map, like this:
final allFilters = {
"filterName1": "someValue",
"filterName2": "someOtherValue",
"fitlerName3": ["value1", "value2", "value3"]
}
And create a function that can handle each key of this map:
allFilter.forEach((key, value) {
switch(key) {
case "filterName1":
// ...some code
case "fitlerName2":
// ...more code
case "filterName3":
// ...much more code
}
})
You can check this demo project that I created https://github.com/felipeemidio/ListWithMultipleFilters

Customizing searchBarController in Flappy Search Bar Flutter

I am currently using Flappy Search Bar for my Flutter app.
I got the search right, but I can't seem to find a example of customizing the SearchBarController for Flappy Search Bar.
I am trying to do a sort function, and the Flappy library says SearchBarController will do the job.
Any links or tutorials I can refer to?
It would be better if anyone has some code they did regarding this controller that I can learn from.
Any help would be much appreciated,
Thanks in advance ;)
You can copy paste run full code below
To do sort you can use sortList and pass a function
signature void sortList(int Function(T a, T b) sorting)
code snippet
_searchBarController.sortList((Post a, Post b) {
return a.body.compareTo(b.body);
});
working demo
full code
import 'dart:math';
import 'package:flappy_search_bar/flappy_search_bar.dart';
import 'package:flappy_search_bar/scaled_tile.dart';
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(
home: Home(),
);
}
}
class Post {
final String title;
final String body;
Post(this.title, this.body);
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final SearchBarController<Post> _searchBarController = SearchBarController();
bool isReplay = false;
Future<List<Post>> _getALlPosts(String text) async {
await Future.delayed(Duration(seconds: text.length == 4 ? 10 : 1));
if (isReplay) return [Post("Replaying !", "Replaying body")];
if (text.length == 5) throw Error();
if (text.length == 6) return [];
List<Post> posts = [];
var random = new Random();
for (int i = 0; i < 10; i++) {
posts.add(Post("$text $i", "body random number : ${random.nextInt(100)}"));
}
return posts;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SearchBar<Post>(
searchBarPadding: EdgeInsets.symmetric(horizontal: 10),
headerPadding: EdgeInsets.symmetric(horizontal: 10),
listPadding: EdgeInsets.symmetric(horizontal: 10),
onSearch: _getALlPosts,
searchBarController: _searchBarController,
placeHolder: Text("placeholder"),
cancellationWidget: Text("Cancel"),
emptyWidget: Text("empty"),
indexedScaledTileBuilder: (int index) => ScaledTile.count(1, index.isEven ? 2 : 1),
header: Row(
children: <Widget>[
RaisedButton(
child: Text("sort"),
onPressed: () {
_searchBarController.sortList((Post a, Post b) {
return a.body.compareTo(b.body);
});
},
),
RaisedButton(
child: Text("Desort"),
onPressed: () {
_searchBarController.removeSort();
},
),
RaisedButton(
child: Text("Replay"),
onPressed: () {
isReplay = !isReplay;
_searchBarController.replayLastSearch();
},
),
],
),
onCancelled: () {
print("Cancelled triggered");
},
mainAxisSpacing: 10,
crossAxisSpacing: 10,
crossAxisCount: 2,
onItemFound: (Post post, int index) {
return Container(
color: Colors.lightBlue,
child: ListTile(
title: Text(post.title),
isThreeLine: true,
subtitle: Text(post.body),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Detail()));
},
),
);
},
),
),
);
}
}
class Detail extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
Text("Detail"),
],
),
),
);
}
}

Collect user input data - flutter

I want to collect input data from the user and record it in a certain page. You will see what my program does (full code down below). But the code below, is having two problems.
first problem: The Data in the HistoryPage class is not getting stored correctly. For example when I press A then type 50, The HistoryPage will store it as 'Subtracted 50 on A (and the date)'. But when I enter a second input, such as 30 on B, the Page will show 'Subtracted 30 on A', 'Subtracted 30 on B'. Thus, the Value of A also changes.
Second problem:
count++;
print(count);
historyList.add(History(data: text.data, dateTime: DateTime.now()));
This part of the code is not working. I tried to make 'text' a global variable. But I cannot change the constructor in the class Tile with a global variable.
full code:
import 'package:flutter/material.dart';
import './globals.dart' as globals;
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HistoryPage()),
);
},
child: Text(value.toString()),
),
FlatButton(
child: Center(child: Text("Spent")),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type()),
);
},
)
],
));
}
}
class Spent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Tile(
text: Text(
"A",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"B",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"C",
style: TextStyle(fontSize: 20.0),
),
),
]))));
}
}
class Tile extends StatelessWidget {
final Text text;
Tile({this.text});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type()),
);
},
child: text,
);
}
}
class Type extends StatefulWidget {
#override
TypeState createState() => TypeState();
}
class TypeState extends State<Type> {
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
keyboardType: TextInputType.number),
FlatButton(
child: Text("Subract"),
onPressed: () {
if (int.tryParse(_controller.text) == null) return;
globals.enteredValue = int.parse(_controller.text);
setState(() {
value -= globals.enteredValue;
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
count++;
print(count);
historyList.add(History(data: text.data, dateTime: DateTime.now()));
},
),
])),
));
}
}
int value = 0;
int count = 0;
List<History> historyList = [];
class History {
String data;
DateTime dateTime;
History({
this.data,
this.dateTime,
});
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}),
),
body: Container(
child: ListView.builder(
itemCount: historyList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
' Subtracted ${globals.enteredValue} on ${historyList[index].data} ${historyList[index].dateTime.toString()}'),
);
},
),
));
}
}
globals.dart
library numbers.globals;
int enteredValue = 0;
You can copy paste run full code below
Step 1: class History add enteredValue attribute
class History {
int enteredValue;
Step 2: historyList.add need enteredValue
historyList.add(History(
enteredValue: int.parse(_controller.text),
Step 3: class Type need final Text text;
class Type extends StatefulWidget {
final Text text;
Type({this.text});
Step 4: MaterialPageRoute(builder: (context) => Type(text: text)),
working demo
full code
import 'package:flutter/material.dart';
import './globals.dart' as globals;
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HistoryPage()),
);
},
child: Text(value.toString()),
),
FlatButton(
child: Center(child: Text("Spent")),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Spent()),
);
},
)
],
));
}
}
class Spent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Tile(
text: Text(
"A",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"B",
style: TextStyle(fontSize: 20.0),
),
),
Tile(
text: Text(
"C",
style: TextStyle(fontSize: 20.0),
),
),
]))));
}
}
class Tile extends StatelessWidget {
final Text text;
Tile({this.text});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Type(text: text)),
);
},
child: text,
);
}
}
class Type extends StatefulWidget {
final Text text;
Type({this.text});
#override
TypeState createState() => TypeState();
}
class TypeState extends State<Type> {
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.pop(context)),
),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
keyboardType: TextInputType.number),
FlatButton(
child: Text("Subract"),
onPressed: () {
if (int.tryParse(_controller.text) == null) return;
globals.enteredValue = int.parse(_controller.text);
setState(() {
value -= globals.enteredValue;
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
count++;
print(count);
historyList.add(History(
enteredValue: int.parse(_controller.text),
data: widget.text.data,
dateTime: DateTime.now()));
},
),
])),
));
}
}
int value = 0;
int count = 0;
List<History> historyList = [];
class History {
int enteredValue;
String data;
DateTime dateTime;
History({
this.enteredValue,
this.data,
this.dateTime,
});
}
class HistoryPage extends StatefulWidget {
#override
HistoryPageState createState() => HistoryPageState();
}
class HistoryPageState extends State<HistoryPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}),
),
body: Container(
child: ListView.builder(
itemCount: historyList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
' Subtracted ${historyList[index].enteredValue} on ${historyList[index].data} ${historyList[index].dateTime.toString()}'),
);
},
),
));
}
}

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);
},
),
);
}
}