How to add specific text and images after the search result page? - flutter

The code below is as far as I have gotten so far. The search function works and when clicking on let's say "Google" you will come to a new page specific to "Google".
But I am unsure now how I can add specific text and images to the page. I for example don't want Facebook information to be put on a Google page. Is the smart to make a new List? What other options are there and how would I go about doing so?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Search Example"),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: SearchItem());
}),
],
),
);
}
}
final List<String> myList = [
"google",
"IOS",
"Android",
"Linux",
"MacOS",
"Windows"
];
class SearchItem extends SearchDelegate<String> {
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
})
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {}
#override
Widget buildSuggestions(BuildContext context) {
final suggestionsList = query.isEmpty
? myList
: myList
.where((p) => p.toLowerCase().contains(query.toLowerCase()))
.toList();
return ListView.builder(
itemBuilder: (context, index) => ListTile(
onTap: () {
close(context, suggestionsList[index]);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(myList
.indexWhere((item) => item == suggestionsList[index]))));
},
title: Text(suggestionsList[index]),
),
itemCount: suggestionsList.length,
);
}
}
class DetailScreen extends StatelessWidget {
final int index;
DetailScreen(this.index);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("${myList[index]}"),),
body: Center(
child: Text(
"${myList[index]}",style: TextStyle(fontSize: 22),
),
));
}
}

Not Sure What you are trying to say, But If you Want to show more number of items on the Details Page, then in That Case you Can Create A class Which can Have all those items included in it, Which you want to show the in the details class.
Here is the working Code For the same, Please check
import 'package:flutter/material.dart';
//Below it the new Class you Will Need, or We can say a Modal You Need to have all your properties of the class,
//Which you wanna show in details page
class MyPlatforms {
String name;
String image;
MyPlatforms({this.image, this.name});
}
//A MyPlatforms list created using that modal
final List<MyPlatforms> myPlatformsList = [
MyPlatforms(image: "assets/images/google.png", name: "Google"),
MyPlatforms(image: "assets/images/ios.png", name: "IOS"),
MyPlatforms(image: "assets/images/linux.png", name: "Linux"),
MyPlatforms(image: "assets/images/android.png", name: "Android"),
MyPlatforms(image: "assets/images/mac.png", name: "MacOS"),
MyPlatforms(image: "assets/images/windows.png", name: "Windows"),
];
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Search Example"),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: SearchItem());
}),
],
),
);
}
}
final List<String> myList = [
"google",
"IOS",
"Android",
"Linux",
"MacOS",
"Windows"
];
class SearchItem extends SearchDelegate<String> {
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
})
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {}
#override
Widget buildSuggestions(BuildContext context) {
final suggestionsList = query.isEmpty
? myList
: myList
.where((p) => p.toLowerCase().contains(query.toLowerCase()))
.toList();
return ListView.builder(
itemBuilder: (context, index) => ListTile(
onTap: () {
close(context, suggestionsList[index]);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(
item: myPlatformsList[
index], //pass the index of the MyPlatforms list
)));
},
title: Text(suggestionsList[index]),
),
itemCount: suggestionsList.length,
);
}
}
class DetailScreen extends StatelessWidget {
final MyPlatforms
item; //Get the item, as a object of MyPlatforms class so the we can acess its all properties like image and name;
DetailScreen({this.item});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("${item.name}"),
),
body: Center(
child: new Column(
children: [
Text(
"${item.name}", //acessing the name property of the MyPlatforms class
style: TextStyle(fontSize: 22),
),
SizedBox(
height: 20.0,
),
Image.asset(
"${item.image}"), //acessing the image property of the MyPlatforms class
],
),
));
}
}

Related

Implementation of basic flutter search bar failed

So I followed a tutorial on how to implement a basic Flutter search bar with search Delegation. You can find the tutorial on this link: https://www.youtube.com/watch?v=FPcl1tu0gDs
class DataSearch extends SearchDelegate<String>{
final wordssuggest=["Word1","Word2"];
final recentwords=["Word1"];
#override
List<Widget> buildActions(BuildContext context){
return [
IconButton(onPressed: (){
query=" ";
}, icon: Icon(Icons.clear))
];
//actions for appbar
}
#override
Widget buildLeading(BuildContext context){
return IconButton(onPressed: (){
close(context, null);
}, icon: Icon(Icons.search));
//leasding icon on the left of the app bar
}
#override
Widget buildResults(BuildContext context){
//show some result
return Container(
color: Colors.grey,
height: 200,
width: 200,
child: Center(child: Text(query),)
);
}
#override
Widget buildSuggestions(BuildContext context){
//show suggestions
final suggestionList =query.isEmpty?
recentwords:wordssuggest.where((p)=>p.startsWith(query)).toList();
return ListView.builder(itemBuilder: (context, index)=>ListTile(
onTap:(){
showResults(context);
} ,
leading: Icon(Icons.work_rounded),
title: RichText(text: TextSpan(text: suggestionList[index].substring(0, query.length),
style: TextStyle(color:Colors.blue, fontWeight: FontWeight.bold),
children: [TextSpan(
text:suggestionList[index].substring(query.length),
style:TextStyle(color:Colors.grey)
)]),
)
),
itemCount: suggestionList.length,);
}
}
However, what is not working for me:
For SearchDelegate method in the DataSearch class:
'Methods must have an explicit list of parameters.Try adding a parameter list.dart(missing_method_parameters)'
For buildActions, buildLeading, builduggestions and buildResults Widgets:
'The declaration 'buildActions' isn't referenced.'
Inside buildSuggestions:
The method 'showResults' isn't defined for the type '_MainPageState'.
Inside buildLeading:
The method 'close' isn't defined for the type '_MainPageState'.
Please help
Maybe your problem is occur because of calling the search delegate class.
this code solve your problem!
import 'package:flutter/material.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: Secondpage(title: 'Flutter Demo Home Page'),
);
}
}
class Secondpage extends StatelessWidget {
final String title;
Secondpage({required this.title});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
actions: [
IconButton(icon: Icon(Icons.add), onPressed: () async {
await showSearch<String>(
context: context,
delegate: DataSearch(),
);
},
)
],
));
}
}
Search Delegate
class DataSearch extends SearchDelegate<String>{
final wordSuggest=["Word1","Word2","Word3","Word4", "Word5","Word6", ];
final recentWords=["Word1"];
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
// showSuggestions(context);
},
),
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, 'null');
},
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
);
}
#override
Widget buildResults(BuildContext context){
//show some result
return Container(
color: Colors.grey,
height: 200,
width: 200,
child: Center(child: Text(query),)
);
}
#override
Widget buildSuggestions(BuildContext context){
//show suggestions
final suggestionList =query.isEmpty?
recentWords:wordSuggest.where((p)=>p.startsWith(query)).toList();
return ListView.builder(itemBuilder: (context, index)=>ListTile(
onTap:(){
showResults(context);
} ,
leading: Icon(Icons.work_rounded),
title: RichText(text: TextSpan(text: suggestionList[index].substring(0, query.length),
style: TextStyle(color:Colors.blue, fontWeight: FontWeight.bold),
children: [TextSpan(
text:suggestionList[index].substring(query.length),
style:TextStyle(color:Colors.grey)
)]),
)
),
itemCount: suggestionList.length,);
}
}

How to update the ListView after a new object has been inserted into list?

I tried to use GetBuilder to update the state but is not working.
The new object is visible in the list if I perform a hot reload, but the page is not populating with the new items. Should I reload the page or should I use reactive Observable?
Also when I try to make the food list observable with foodList.obs - I get an error because I can not make food type objects observable. Very strange.
class FoodsController extends GetxController {
List<Food> foodList = [];
int nrOfFoods;
onInit() {
foodList.add(Food(name: 'banana', type: 'fruits'));
foodList.add(Food(name: 'apples', type: 'fruits'));
foodList.add(Food(name: 'melon', type: 'fruits'));
super.onInit();
}
#override
void onReady() {
nrOfFoods.obs;
super.onReady();
}
void addItem(Food item) {
foodList.add(item);
nrOfFoods = foodList.length;
update();
}
}
class HomePage extends StatelessWidget {
FoodsController foodsController = Get.put(FoodsController());
#override
Widget build(BuildContext context) {
print(foodsController.foodList);
return Scaffold(
appBar: AppBar(
title: Text('App Bar'),
),
body: Column(
children: [
Expanded(
child: GetBuilder<FoodsController>(
init: FoodsController(),
builder: (_) => ListView.builder(
itemCount: foodsController.foodList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(foodsController.foodList[index].name));
},
),
),
),
FloatingActionButton(
child: Text("test"),
onPressed: () => {
foodsController.foodList.add(Food(name: "chicken", type: "meat")),
Get.to(SecondPage())
},
),
],
),
);
}
}
Thank you
I found a solution. I moved the controller to the second page and now is ok though I think I should use Obx instead of GetBuilder to make this reactive.
class Food {
Food({this.name, this.type});
String name, type;
#override
String toString() => '${this.name} is a ${this.type}';
}
class FoodsController extends GetxController {
final List<Food> foodList = [];
int nrOfFoods = 0;
onInit() {
foodList.add(Food(name: 'banana', type: 'fruits'));
foodList.add(Food(name: 'apples', type: 'fruits'));
foodList.add(Food(name: 'melon', type: 'fruits'));
super.onInit();
}
void addItem(Food item) {
foodList.add(item);
nrOfFoods = foodList.length;
update();
}
}
class HomePage extends StatelessWidget {
final FoodsController foodsController = Get.put(FoodsController());
#override
Widget build(BuildContext context) {
print(foodsController.foodList);
return Scaffold(
appBar: AppBar(
title: Text('App Bar'),
),
body: Column(
children: [
FloatingActionButton(
child: Text("test"),
onPressed: () {
foodsController.foodList.add(Food(name: "chicken", type: "meat"));
Get.to(SecondPage());
},
),
],
),
);
}
}
class SecondPage extends StatelessWidget {
final FoodsController ctrl = Get.find();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('App Bar'),
),
body: Column(
children: [
Expanded(
child: GetBuilder<FoodsController>(
builder: (_) => ListView.builder(
itemCount: ctrl.foodList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(title: Text(ctrl.foodList[index].name));
},
),
),
),
FloatingActionButton(
child: Text("test"),
onPressed: () {
ctrl.foodList.add(Food(name: "chicken", type: "meat"));
Get.to(SecondPage());
},
),
],
),
);
}
}
Thank you

Flutter CupertinoActionSheet: how to define Variable number of actions

Depending on number of entries in List distinctEmnen,
I would like to show variable number of menu-choices.
Is it possible to achieve something like this?
CupertinoActionSheet(
title: Text( tjo),
actions: [
CupertinoActionSheetAction(
child: Text( distinctEmnen[0]),
Navigator.of(context).pushNamed(distinctEmnen[0]);
}),
CupertinoActionSheetAction(
child: Text( distinctEmnen[1]),
onPressed: () {
Navigator.of(context).pushNamed(distinctEmnen[1]);
}),
CupertinoActionSheetAction(
child: Text( distinctEmnen[n...]),
onPressed: () {
Navigator.of(context).pushNamed(distinctEmnen[n...]);
}),
],
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
),
You can copy paste run full code below
Step 1: You can define a class Emnen
Step 2: Init List<Emnen> distinctEmnen
Step 3: Use List<Widget>.generate(distinctEmnen.length,
code snippet
class Emnen {
String title;
String routeName;
Emnen({this.title, this.routeName});
}
...
List<Emnen> distinctEmnen = [];
...
#override
void initState() {
distinctEmnen = [
Emnen(title: "1", routeName: "/1"),
Emnen(title: "2", routeName: "/2")
];
super.initState();
}
...
CupertinoActionSheet(
title: Text("tjo"),
actions: List<Widget>.generate(
distinctEmnen.length,
(int index) => CupertinoActionSheetAction(
child: Text(distinctEmnen[index].title),
onPressed: () => Navigator.of(context)
.pushNamed(distinctEmnen[index].routeName))));
working demo
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class Emnen {
String title;
String routeName;
Emnen({this.title, this.routeName});
}
class CupertinoActionSheetApp extends StatelessWidget {
#override
Widget build(BuildContext context) => CupertinoApp(
initialRoute: "/",
routes: {
'/': (context) => HomePage(),
'/1': (context) => FirstScreen(),
'/2': (context) => SecondScreen(),
},
);
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Emnen> distinctEmnen = [];
#override
void initState() {
distinctEmnen = [
Emnen(title: "1", routeName: "/1"),
Emnen(title: "2", routeName: "/2")
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Center(
child: CupertinoButton(
child: Text("show dialog"),
onPressed: () {
_showDialog(context);
}),
);
}
void _showDialog(BuildContext cxt) {
showCupertinoModalPopup<int>(
context: cxt,
builder: (cxt) {
var dialog = CupertinoActionSheet(
title: Text("tjo"),
actions: List<Widget>.generate(
distinctEmnen.length,
(int index) => CupertinoActionSheetAction(
child: Text(distinctEmnen[index].title),
onPressed: () => Navigator.of(context)
.pushNamed(distinctEmnen[index].routeName))));
return dialog;
});
}
}
void main() {
runApp(CupertinoActionSheetApp());
}
class FirstScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text("Cupertino App"),
),
child: Center(
child: Text("First"),
),
);
}
}
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text("Cupertino App"),
),
child: Center(
child: Text("Second"),
),
);
}
}
full code

Bottom tab navigator show up when I click back button from my phone in flutter

Hi I am new in flutter and right now I try to declare my data for all tabs with this code, but when I click tab, the bottom navigator is dismiss and show up again when I click back button from my phone, is there anyone know the mistakes or the problems?
class BottomTab extends StatefulWidget {
final String text;
BottomTab({this.text});
#override
_BottomTabState createState() => _BottomTabState();
}
class _BottomTabState extends State<BottomTab> {
void initState() {
super.initState();
}
_onTap(int index) {
setState(() => _selectedIndex = index);
if (index == 0) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new HomeScreen(value: widget.value)));
} else if (index == 1) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new FirstPage(value: widget.value)));
} else {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new HomeScreen(value: widget.value)));
}
}
final List<Widget> pages = [
HomeScreen(),
FirstPage(),
];
final PageStorageBucket bucket = PageStorageBucket();
int _index = 0;
Widget _myList(int index) => BottomNavigationBar(
onTap: _onTap,
currentIndex: index,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.more), title: Text('More')),
],
);
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _myList(_index),
body: PageStorage(
child: pages[_index],
bucket: bucket,
),
);
}
}
You can copy paste run full code below
In your case, you do not need Navigator.push and change this line
From
setState(() => _selectedIndex = index);
To
setState(() => _index = index);
working demo
full code
import 'package:flutter/material.dart';
class BottomTab extends StatefulWidget {
final String text;
BottomTab({this.text});
#override
_BottomTabState createState() => _BottomTabState();
}
class _BottomTabState extends State<BottomTab> {
void initState() {
super.initState();
}
_onTap(int index) {
setState(() => _index = index);
/*if (index == 0) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new HomeScreen(value: widget.value)));
} else if (index == 1) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new FirstPage(value: widget.value)));
} else {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new HomeScreen(value: widget.value)));
}*/
}
final List<Widget> pages = [
HomeScreen(),
FirstPage(),
];
final PageStorageBucket bucket = PageStorageBucket();
int _index = 0;
Widget _myList(int index) => BottomNavigationBar(
onTap: _onTap,
currentIndex: index,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.more), title: Text('More')),
],
);
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _myList(_index),
body: PageStorage(
child: pages[_index],
bucket: bucket,
),
);
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("demo"),
),
body: Text("HomesScreen"));
}
}
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("demo"),
),
body: Text("FirstPage"));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BottomTab(),
);
}
}
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.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

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