How to refer multiple values sepererately in flutter firebase? - android

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Authentication (),
);
}
}
class Authentication extends StatelessWidget {
const Authentication({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot){
if(!snapshot.hasData){
return const SignInScreen(
providerConfigs: [
EmailProviderConfiguration()
],
);
}
return const Diarymain ();
},
);
}
}
class Diarymain extends StatefulWidget {
const Diarymain({Key? key}) : super(key: key);
#override
State<Diarymain> createState() => _DiarymainState();
}
class _DiarymainState extends State<Diarymain> {
final fbs = FirebaseDatabase.instance;
var currentUser = FirebaseAuth.instance.currentUser;
#override
Widget build(BuildContext context) {
final ref = fbs.ref().child('diary').child(currentUser!.uid);
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.grey[350],
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => AddEditDiary(),
),
);
},
child: const Icon(
Icons.add,
),
),
appBar: AppBar(title: Text('Diary'),),
body: FirebaseAnimatedList(
query: ref,
shrinkWrap: true,
itemBuilder: (context, snapshot, animation, index) {
return GestureDetector(
onTap: () {},
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
// child: ListView.builder(
// itemBuilder: (context, index) {
child: ListTile(
shape: RoundedRectangleBorder(
side: const BorderSide(
color: Colors.white,
),
borderRadius: BorderRadius.circular(10),
),
tileColor: Colors.blue[50],
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.blueGrey[900],
),
onPressed: () {
ref.child(snapshot.key!).remove();
},
),
title: Text(
snapshot.value.toString(),
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
// },)
),
),
);
},
),
);
}
}
class AddEditDiary extends StatefulWidget {
const AddEditDiary({Key? key}) : super(key: key);
#override
State<AddEditDiary> createState() => _AddEditDiaryState();
}
class _AddEditDiaryState extends State<AddEditDiary> {
TextEditingController title = TextEditingController();
TextEditingController subtitle = TextEditingController();
final fbs = FirebaseDatabase.instance;
var currentUser = FirebaseAuth.instance.currentUser;
#override
Widget build(BuildContext context) {
final ref = fbs.ref().child('diary').child(currentUser!.uid);
return Scaffold(
appBar: AppBar(title: Text('Add'),),
body: ListView(
children: <Widget> [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: title,
decoration: InputDecoration(
labelText: 'Title',
hintText: 'Enter Title',
border: OutlineInputBorder(),
),
)
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: subtitle,
decoration: InputDecoration(
labelText: 'Subtitle',
hintText: 'Enter Subtitle',
border: OutlineInputBorder(),
),
)
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {
ref
.push()
.set({
'title' : title.text,
'subtitle' : subtitle.text,
})
.asStream();
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (_) => Diarymain()));
},
child: Text('Save', style: TextStyle(color: Colors.white),),
color: Colors.pink,
),
)
]
)
);
}
}
I'm trying to make a diary and two things which are title and subtitle are stored in the firebase real-time database. Below part of code shows how they are added in the firebase.
child: RaisedButton(
onPressed: () {
ref
.push()
.set({
'title' : title.text,
'subtitle' : subtitle.text,
})
.asStream();
When title and subtitles are shown on the page, I want to show them separately and I think I need something value to refer them individually.
In my code, "snapshot.value.toString()," shows only both title and subtitle together.
Is there any way to indicate them separately?
I would appreciate it if anyone can help me with this.

Related

How can I get the Navigator to work in Flutter?

I'm new on Flutter, so obviously I'm messing up somewhere in the code that I'm not being able to figure out. Basically I have a login screen from which I want to navigate to a second screen, but when I select the button absolutely nothing happens, nor does an error appear. I have been looking all over for an answer but none of them can solve the problem. I hope someone can help me. (The texts of the buttons are in Spanish).
This is the main.dart:
import 'package:flutter/material.dart';
import 'package:go_out/screens/screens.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: 'home',
routes: {
'home': (_) => const HomeScreen(),
'signInEmail': (_) => const SignInEmail(),
},
);
}
}
This is the home_screen.dart:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../widgets/widgets.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: Colors.black,
body: Padding(
padding: EdgeInsets.only(left: 15, right: 15),
child: Center(
child: _SignInPageDesign(),
),
),
);
}
}
class _SignInPageDesign extends StatelessWidget {
const _SignInPageDesign({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10, right: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'images/logo.png',
height: 200,
fit: BoxFit.cover,
),
const SizedBox(
height: 30,
),
CustomElevatedButtonWithoutIcon(
text: 'Crear Cuenta',
onPressed: () => Navigator.pushNamed(context, 'signInEmail'),
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Facebook',
onPressed: () {},
icon: FontAwesomeIcons.facebookSquare,
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Google',
onPressed: () {},
icon: FontAwesomeIcons.google,
),
const SizedBox(height: 12),
CustomElevatedButtonWithIcon(
text: 'Continuar con Apple',
onPressed: () {},
icon: FontAwesomeIcons.apple,
),
const SizedBox(height: 12),
const CustomTextButton(
text: 'Iniciar sesiĆ³n',
),
const SizedBox(height: 12),
CustomElevatedButtonWithoutIcon(
text: 'Registrar comercio',
onPressed: () {},
),
],
),
);
}
}
This is the problem with home_screen.dart which does not return any value.
CustomElevatedButtonWithoutIcon(
text: 'Crear Cuenta',
onPressed: () => Navigator.pushNamed(context, 'signInEmail'),
),
This is the second screen I want to go to sign_in_email.dart:
import 'package:flutter/material.dart';
class SignInEmail extends StatelessWidget {
const SignInEmail({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromRGBO(254, 80, 0, 1),
),
);
}
}
This is the class CustomElevatedButtonWithoutIcon:
import 'package:flutter/material.dart';
class CustomElevatedButtonWithoutIcon extends StatelessWidget {
const CustomElevatedButtonWithoutIcon({
Key? key,
required this.text,
required this.onPressed,
}) : super(key: key);
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text(
text,
style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
onPressed: () {},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all<Size>(const Size(0, 50)),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromRGBO(254, 80, 0, 1)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
),
),
);
}
}
You didn't pass anything onPressed funciton, you kept it empty, so nothing was working, just pass your onPressed function inside ElevatedButton like below
import 'package:flutter/material.dart';
class CustomElevatedButtonWithoutIcon extends StatelessWidget {
const CustomElevatedButtonWithoutIcon({
Key? key,
required this.text,
required this.onPressed,
}) : super(key: key);
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text(
text,
style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
onPressed: onPressed,
style: ButtonStyle(
fixedSize: MaterialStateProperty.all<Size>(const Size(0, 50)),
backgroundColor: MaterialStateProperty.all<Color>(
const Color.fromRGBO(254, 80, 0, 1)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
),
),
);
}
}
Also it's best practice to use RouteGenerator, create a route_generator.dart file with the following code below
import 'package:flutter/material.dart';
class RouterCustom {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case "home":
return MaterialPageRoute(
builder: (_) => const HomeScreen(),
settings: const RouteSettings(name: "home"),
);
case "signInEmail":
return MaterialPageRoute(
builder: (_) => const SignInEmail(),
settings: const RouteSettings(name: "signInEmail"),
);
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
),
settings: const RouteSettings(name: "404"),
);
}
}
}
Then pass it to your main method's router param
MaterialApp(
initialRoute: "home",
onGenerateRoute: RouterCustom.generateRoute,
)
CustomElevatedButtonWithoutIcon doesn't actually do anything when pressed, onPressed: () {}, should be onPressed: onPressed,.
A simple way to detect this, is by adding a print statement right before navigating, or adding a breakpoint. If neither is triggered, the function isn't being called and your issue isn't in the Navigation.
Your widget CustomElevatedButtonWithoutIcon is not calling any function after it is being pressed
You have this
onPressed: () {},
Change it for
onPressed: onPressed

How to open this type of alert dialog in flutter

I wanted to show dialog in my application. How can i achieve this using flutter
You can use a PopupMenuButton (https://api.flutter.dev/flutter/material/PopupMenuButton-class.html) to achieve this in flutter.
See example code below:
PopupMenuButton<int>(
itemBuilder: (context) => [
const PopupMenuItem(
value: 1,
child: Center(
child: Icon(
Icons.download_outlined,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.link,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.share,
size: 30.0,
),
),
),
],
icon: const Icon(
Icons.more_horiz,
size: 40.0,
),
offset: const Offset(150, -150),
);
The above example popups a list of Icons when the PopupMenuButton is pressed.
You can adapt this to your use-case above.
Finally I found a Solution thanks enfinity. Here how i solve the problem.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
/// An arbitrary widget that lives in a popup menu
class PopupMenuWidget<T> extends PopupMenuEntry<T> {
const PopupMenuWidget({ Key key, this.height, this.child }) : super(key: key);
#override
final Widget child;
#override
final double height;
#override
bool get enabled => false;
#override
_PopupMenuWidgetState createState() => new _PopupMenuWidgetState();
}
class _PopupMenuWidgetState extends State<PopupMenuWidget> {
#override
Widget build(BuildContext context) => widget.child;
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
actions: <Widget>[
new PopupMenuButton<String>(
onSelected: (String value) {
print("You selected $value");
},
itemBuilder: (BuildContext context) {
return [
new PopupMenuWidget(
height: 40.0,
child: new Row(
children: [
IconButton(
icon: Icon(
Icons.remove,
color: Colors.green,
),
onPressed: () {
print("Remove");
}),
Text("1"),
IconButton(
icon: Icon(
Icons.add,
color: Colors.green,
),
onPressed: () {
print("Add");
}),
],
),
),
];
}
),
],
),
);
}
}

Make a list out of arguments received from second page in the home page

I am new to Flutter and I am creating a notes app. i want to pass the title and text of the new note from a "new note" page to the home page where all other notes are.
I want to pass the title and text to the first page where I can create a list of saved notes as the number of notes grow using a List view. What am I doing wrong?
Here is my code for the home page:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:notes/newnote.dart';
void main() {
runApp(MaterialApp(home: MyApp(), initialRoute: 'main.dart', routes: {
'/home': (context) => MyApp(),
'/newnote': (context) => NewNote(),
}));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Notes',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstPage(),
);
}
}
int x = 0;
class FirstPage extends StatefulWidget {
String title ;
String text ;
FirstPage({Key key, #required this.title,#required this.text}) : super(key: key);
void pri() {print(title);}
#override
_MyAppState createState() => _MyAppState();
}
Map data = {};
class _MyAppState extends State<FirstPage> {
#override
Widget build(BuildContext context) {
//final dat args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text(
"Note-It!",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.black,
),
body: Column(
//
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(19.0, 19.0, 19.0, 19.0),
),
Expanded(
child: ListView.builder(
itemCount: x,
itemBuilder: (context, index) {
return ListTile(
title: Text(widget.title),
// onTap: () {
// Navigator.push( context,MaterialPageRoute( builder: (context) =>
// DetailScreen(notedata: datas[index])));
// }
);
}),
),
Align(
alignment: Alignment.bottomRight,
child: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.black,
onPressed: () {
setState(() {
Navigator.push(context, new MaterialPageRoute(
builder: (context) =>
new NewNote(t1: null, t2: null)
));
});
}),
),
],
),
);
}
}
and here is my code for "new note" page
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:notes/main.dart';
void main() {
runApp(MaterialApp(home: NewNote()));
}
final fromController1 = TextEditingController();
final fromController2 = TextEditingController();
var instance;
class NewNote extends StatelessWidget {
String t1; //requesting data here
String t2;
NewNote({Key key, #required this.t1,#required this.t2}) : super(key: key);
// final String d;
//
// NewNote({
// Key key,
// #required this.d,
// }) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("New Note"),
backgroundColor: Colors.black,
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.fromLTRB(19.0, 19.0, 19.0, 19.0),
child: SingleChildScrollView(
child: Column(children: <Widget>[
TextField(
controller: fromController1,
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: "Title"),
style: TextStyle(fontSize: 28.0),
),
Padding(padding: EdgeInsets.fromLTRB(19.0, 19.0, 19.0, 0.0)),
TextField(
controller: fromController2,
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: "Text"),
style: TextStyle(fontSize: 20.0),
maxLines: null,
),
Padding(padding: EdgeInsets.fromLTRB(19.0, 19.0, 19.0, 0.0)),
Align(
alignment: Alignment.bottomCenter,
child: FloatingActionButton.extended(
label: Text("Save Note"),
icon: Icon(Icons.save),
backgroundColor: Colors.black,
onPressed: () {
x++;
t1 = fromController1.text;
t2 = fromController2.text;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyApp(), //pass your title and text to NewNote
),
).then((value){
FirstPage(title: t1, text: t2);
});
},
),
),
]),
),
),
),
);
}
}
You have already passed the title and string in the first page from new note page. You are just not displaying it onto the screen with right syntax.
Change this
title: Text(
"Note-It!",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
to
title: Text(
this.widget.title,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),

Stuck on being able to view detailed information from a list in flutter app

I have a louded information in RealTime database in format for example:
record
0
Club: "Club1"
Name: "Ronaldo"
Place: "London"
date: "25.07.2020"
email: "flutter#gmail.com"
phone: "12345678"
I have created a list that consists of names and clubs and I want to go to the full information according to the form by clicking on the Name, but I can't write the code. Please help to the new programmer
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:.../anketa/tile.dart';
class Anketa extends StatefulWidget {
Anketa({Key key, this.title}) : super(key: key);
final String title;
#override
_AnketaState createState() => _AnketaState();
}
class _AnketaState extends State<Anketa> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Registration form",
style: TextStyle(
fontWeight: FontWeight.w200,
fontSize: 30,
fontFamily: 'Roboto',
fontStyle: FontStyle.italic)),
RegisterStudent(),
]),
)),
);
}
}
class RegisterStudent extends StatefulWidget {
RegisterStudent({Key key}) : super(key: key);
#override
_RegisterStudentState createState() => _RegisterStudentState();
}
class _RegisterStudentState extends State<RegisterStudent> {
final _formKey = GlobalKey<FormState>();
final listOfClubs = ["Club1", "Club2", "Club3", "Club4"];
String dropdownValue = "Club1";
final clubController = TextEditingController();
final nameController = TextEditingController();
final placeController = TextEditingController();
final dateController = TextEditingController();
final emailController = TextEditingController();
final phoneController = TextEditingController();
final rawController = TextEditingController();
final dbRef = FirebaseDatabase.instance.reference().child("record");
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: "EnterName",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return "Enter name";
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: DropdownButtonFormField(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
decoration: InputDecoration(
labelText: "Club",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
items: listOfClubs.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
this.dropdownValue = newValue;
});
},
validator: (value) {
if (value.isEmpty) {
return 'Club';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
keyboardType: TextInputType.number,
controller: dateController,
decoration: InputDecoration(
labelText: "Date",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Date';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
color: Colors.lightBlue,
onPressed: () {
if (_formKey.currentState.validate()) {
dbRef.push().set({
"Name": nameController.text,
"date": dateController.text,
"Club": dropdownValue
}).then((_) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Add')));
dateController.clear();
nameController.clear();
}).catchError((onError) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(onError)));
});
}
},
child: Text('Enter'),
),
RaisedButton(
color: Colors.amber,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ListOfNames()),
);
},
child: Text('Go to'),
),
],
)),
])));
}
#override
void dispose() {
super.dispose();
dateController.dispose();
nameController.dispose();
}
}
and this is the second page with a list, from where I want to go to full information
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
class ListOfNames extends StatelessWidget {
final dbRef = FirebaseDatabase.instance.reference().child("record");
List<Map<dynamic,dynamic>> lists = List();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey.shade300,
appBar: AppBar(
backgroundColor: Colors.deepPurple,
title: Text("List of students"),
),
body: StreamBuilder(
stream: dbRef.onValue,
builder: (context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
lists.clear();
DataSnapshot dataValues = snapshot.data.snapshot;
Map<dynamic, dynamic> values = dataValues.value;
values.forEach((key, values) {
lists.add(values);
});
return new ListView.builder(
shrinkWrap: true,
itemCount: lists.length,
itemBuilder: (BuildContext context, int index) {
itemBuilder: (BuildContext context, int index) {
return ListTile(
title:Text(lists[index]["Name"], style: TextStyle(height: 2.5, fontSize:20.0),),
subtitle:Text(lists[index]['Club'], style: TextStyle(fontSize:16.0),),
onTap: (){
// in this line i have a problem...
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(snapshot.data[index]['Name']),
)
);
},
);
});
}
return CircularProgressIndicator();
})
);
}
}
I want to create such a page:
class DetailPage extends StatelessWidget {
List<Map<dynamic,dynamic>> data ;
DetailPage ({this.data});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(data.name),
// here I want to show the all information from the form about one person from the list
),
);
}
}
In the body of the scaffold of 'DetailsPage' use 'Card' widget with 'Text' widgets to show the info. Like Card(child:Text('${data.clubLoc}').

Flutter ListView on click navigate to another screen

I'm learning Flutter. I have a ListView and I would like to make the list items clickable. My idea is that when the user clicks on an item, it will be directed to another screen. Each buttom should leads to different screen. I'm having trouble implementing it, I don't know what to use: gesture detector or ontap. What should I do? Should I use ListTile instead of ListView?
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final title = "ListView List";
return MaterialApp(
title: title,
home: Scaffold(appBar: AppBar(
title: Text(title),
),
body: new ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(20.0),
children: List.generate(choices.length, (index) {
return Center(
child: ChoiceCard(choice: choices[index], item: choices[index]),
);
}
)
)
)
);
}
}
class Choice {
const Choice({this.title, this.icon});
final String title;
final IconData icon;
}
const List<Choice> choices = const <Choice>[
const Choice(title: 'This is a Car', icon: Icons.directions_car),
const Choice(title: 'This is a Bicycle', icon: Icons.directions_bike),
const Choice(title: 'This is a Boat', icon: Icons.directions_boat),
const Choice(title: 'This is a Bus', icon: Icons.directions_bus),
const Choice(title: 'This is a Train', icon: Icons.directions_railway),
];
class ChoiceCard extends StatelessWidget {
const ChoiceCard(
{Key key, this.choice, this.onTap, #required this.item, this.selected: false}
) : super(key: key);
final Choice choice;
final VoidCallback onTap;
final Choice item;
final bool selected;
#override
Widget build(BuildContext context) {
TextStyle textStyle = Theme.of(context).textTheme.display1;
if (selected)
textStyle = textStyle.copyWith(color: Colors.lightGreenAccent[400]);
return Card(
color: Colors.white,
child: Row(
children: <Widget>[
new Container(
padding: const EdgeInsets.all(8.0),
alignment: Alignment.topLeft,
child: Icon(choice.icon, size:80.0, color: textStyle.color,)),
new Expanded(
child: new Container(
padding: const EdgeInsets.all(10.0),
alignment: Alignment.topLeft,
child:
Text(choice.title, style: null, textAlign: TextAlign.left, maxLines: 5,),
)
),
],
crossAxisAlignment: CrossAxisAlignment.start,
)
);
}
}
You can copy paste run full code below
Step 1: To allow Navigator.push work, you can move MaterialApp to upper level
Step 2: In onTap pass Navigator.push
ChoiceCard(
choice: choices[index],
item: choices[index],
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Detail(choice: choices[index])),
);
},
),
Step 3: Wrap Card with InkWell and call onTap()
return InkWell(
onTap: () {
onTap();
},
child: Card(
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatelessWidget {
final title = "ListView List";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: new ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(20.0),
children: List.generate(choices.length, (index) {
return Center(
child: ChoiceCard(
choice: choices[index],
item: choices[index],
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Detail(choice: choices[index])),
);
},
),
);
})));
}
}
class Choice {
const Choice({this.title, this.icon});
final String title;
final IconData icon;
}
const List<Choice> choices = const <Choice>[
const Choice(title: 'This is a Car', icon: Icons.directions_car),
const Choice(title: 'This is a Bicycle', icon: Icons.directions_bike),
const Choice(title: 'This is a Boat', icon: Icons.directions_boat),
const Choice(title: 'This is a Bus', icon: Icons.directions_bus),
const Choice(title: 'This is a Train', icon: Icons.directions_railway),
];
class ChoiceCard extends StatelessWidget {
const ChoiceCard(
{Key key,
this.choice,
this.onTap,
#required this.item,
this.selected: false})
: super(key: key);
final Choice choice;
final VoidCallback onTap;
final Choice item;
final bool selected;
#override
Widget build(BuildContext context) {
TextStyle textStyle = Theme.of(context).textTheme.display1;
if (selected)
textStyle = textStyle.copyWith(color: Colors.lightGreenAccent[400]);
return InkWell(
onTap: () {
onTap();
},
child: Card(
color: Colors.white,
child: Row(
children: <Widget>[
new Container(
padding: const EdgeInsets.all(8.0),
alignment: Alignment.topLeft,
child: Icon(
choice.icon,
size: 80.0,
color: textStyle.color,
)),
new Expanded(
child: new Container(
padding: const EdgeInsets.all(10.0),
alignment: Alignment.topLeft,
child: Text(
choice.title,
style: null,
textAlign: TextAlign.left,
maxLines: 5,
),
)),
],
crossAxisAlignment: CrossAxisAlignment.start,
)),
);
}
}
class Detail extends StatelessWidget {
final Choice choice;
Detail({this.choice});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Column(
children: <Widget>[
Text("${choice.title}"),
Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
],
),
);
}
}
import 'package:easy_buss/screen/client.dart';
import 'package:easy_buss/screen/invoice.dart';
import 'package:easy_buss/screen/invoice_settings.dart';
import 'package:easy_buss/screen/payment_info.dart';
import 'package:easy_buss/widgets/payment_info_form.dart';
import 'package:flutter/material.dart';
class Settings extends StatefulWidget {
#override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
List<IconData> _icon = [
Icons.accessible,
Icons.analytics,
Icons.question_answer_sharp,
Icons.message,
Icons.share,
Icons.star_half,
Icons.add_business,
Icons.privacy_tip,
];
List<String> _title = [
'Invoice Settings',
'Reports',
'Frequently Ask Questions',
'Write Us',
'Share With A Friends',
'Rate Us',
'Terms & Conditions',
'Privacy Policy',
];
List<Color> _colors = [
Colors.cyan,
Colors.yellow,
Colors.red,
Colors.purple,
Colors.orange,
Colors.grey,
Colors.pink[300],
Colors.green[200],
];
List _items = [
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
InvoiceSettings(),
];
#override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: _title.length,
separatorBuilder: (BuildContext context, int index) => Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
),
child: Divider(
thickness: 1,
),
),
itemBuilder: (BuildContext context, int index) => ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _items[index],
),
);
},
leading: Container(
padding: const EdgeInsets.all(5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: _colors[index],
),
child: Icon(
_icon[index],
color: Colors.white,
size: 20,
),
),
title: Text(
_title[index],
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
trailing: Icon(
Icons.chevron_right,
size: 40,
),
),
);
}
}

Categories

Resources