Could not find the correct Provider<TaskData> above this TasksScreenNew Widget - flutter

I have a problem using Flutter Provider... every time when im clicking at the widget that brings me to the Tasksscreen i'm getting this error. Im really new to Provider... got that code from a tutorial. I'm just stuck with this error for 1 hour now and i haven't found anything suitable for my problem.
If you need more code, just say it
Error:
ProviderNotFoundException (Error: Could not find the correct Provider<TaskData> above this TasksScreenNew Widget
Code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:learnon/widgets/tasks_list.dart';
import 'package:learnon/screens/addtasksscreen.dart';
import 'package:learnon/models/tasks_data.dart';
import 'package:provider/provider.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
bool theme = false;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
class TasksScreenNew extends StatelessWidget {
static const routeName = "/tasksnewwidget";
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
floatingActionButton: FloatingActionButton(
heroTag: null,
child: Icon(Icons.add),
backgroundColor: Colors.lightBlue,
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (BuildContext context) => AddTaskScreen());
},
),
body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Container(
padding: EdgeInsets.only(top: 60, left: 30, right: 30, bottom: 30),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 10,
),
Text(
'Todo',
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontWeight: FontWeight.bold),
),
Text(
'${Provider.of<TaskData>(context).taskCount} Tasks',
style: TextStyle(fontSize: 18, color: Colors.white),
),
],
),
),
Expanded(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: TasksList(),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
),
)
]),
);
}
}
// CircleAvatar(
// radius: 30,
// backgroundColor: Colors.white,
// child: Icon(
// Icons.list,
// color: Colors.blueAccent,
// size: 30,
// ),
// )

To access providers from context, you need to wrap any widget higher up the tree in Provider or ChangeNotifierProvider.
You can try doing the following on the current page.
Widget build(BuildContext context) {
return ChangeNotifierProvider<TaskData>(
create: (_) => TaskData(),
builder: (context, __) => Scaffold(
You can also see examples, e.g. here https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

Related

Error : The argument type 'Context' can't be assigned to the parameter type 'BuildContext'

There was a problem with my code, while I was trying to exit a screen of mine from my bus tracking app main page but this is showing an error. I have tried importing everything given in StackOverflow.
help me to get this solved please
import 'dart:js';
import 'package:flutter/services.dart';
import 'registration_screen.dart';
import 'login_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path/path.dart';
class WelcomePage extends StatelessWidget {
From here the function starts
Future<bool?> _onBackPressed() async {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(`enter code here`
title: Text('Do you want to exit?'),
actions: <Widget>[
TextButton(
child: Text('No'),
onPressed: () {
Navigator.of(context).pop(false);
},
),
TextButton(
child: Text('Yes'),
onPressed: () {
Navigator.of(context).pop(true);
SystemNavigator.pop();
},
),
],
);
}
);
}
Scaffold start here also the WillPopScope starts here which returns the _onBackPressed();
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
bool? result = await _onBackPressed();
if (result == null) {
result = false;
}
return result;
},
child: Scaffold(
// return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 20,
),
Lottie.asset('assets/images/bus.json'),
SizedBox(
height: 20,
),
Text(
"Welcome to \n Bus Tracking",
style: GoogleFonts.poppins(
fontSize: 34, fontWeight: FontWeight.w700),
textAlign: TextAlign.center,
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 38),
child: Container(
height: 65,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.3),
spreadRadius: 2,
blurRadius: 3,
offset: Offset(0, 5))
],
color: Colors.deepPurple,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
RegistrationScreen()));
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.deepPurple,
width: 0.9,
)
//textColor: Colors.black87,
),
child: const Center(
child: Text(
'Register',
style: TextStyle(
color: Colors.deepPurple,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
),
),
),
Expanded(
child: GestureDetector(
//bgColor: Colors.transparent,
//buttonName: 'Sign In',
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => LoginScreen(),
));
},
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.deepPurple,
width: 0.9,
)
//textColor: Colors.black87,
),
child: const Center(
child: Text(
'Login',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
),
),
),
],
),
),
),
],
),
),
),
));
}
}
Change the function _onBackPressed as
Future<bool?> _onBackPressed(BuildContext ctx) async {
return showDialog(
context: ctx,
builder: (BuildContext context) {
return AlertDialog(`enter code here`
title: Text('Do you want to exit?'),
actions: <Widget>[
TextButton(
child: Text('No'),
onPressed: () {
Navigator.of(context).pop(false);
},
),
TextButton(
child: Text('Yes'),
onPressed: () {
Navigator.of(context).pop(true);
SystemNavigator.pop();
},
),
],
);
}
);
}
Now in the build function use :
bool? result = await _onBackPressed(context);
context is getting clashed may de due to import 'package:path/path.dart'; if you don't need it remove it.
Here in the question i have been using a stateless widget but I need to use a stateful widget, so the solution is to create a new file as a stateful widget and dumb all this code in it and the error was solved.

InkWell onTap issue regarding "context"

I am developing a news application in flutter using this article below. Everything works fine but in the last step I run into an issue with InkWell's onTap function because of "context."
Inside my code below I surrounded my "context" error with *** *** just for show.
I am going to show three total files.
https://nabendu82.medium.com/flutter-news-app-using-newsapi-2294c2dcf673
HomePage
import 'package:flutter/material.dart';
import 'package:flutter_job_portal/news/model/article_model.dart';
import 'package:flutter_job_portal/news/services/api_service.dart';
import 'package:flutter_job_portal/news/components/customListTile.dart';
class HomeNews extends StatefulWidget {
#override
_HomeNewsState createState() => _HomeNewsState();
}
class _HomeNewsState extends State<HomeNews> {
ApiService client = ApiService();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("News App", style: TextStyle(color: Colors.black)),
backgroundColor: Colors.white),
body: FutureBuilder(
future: client.getArticle(),
builder: (BuildContext context, AsyncSnapshot<List<Article>> snapshot) {
if (snapshot.hasData) {
List<Article> articles = snapshot.data;
return ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) =>
customListTile(articles[index], ***context***)
// ListTile(title: Text(articles[index].title))
// customListTile(
// articles[index],
// context
// )
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
customListTile
// import 'dart:js';
import 'package:flutter/material.dart';
import 'package:flutter_job_portal/news/model/article_model.dart';
import 'package:flutter_job_portal/news/pages/articles_details_page.dart';
Widget customListTile(Article article) {
return InkWell(
onTap: () {
Navigator.push(
***context***,
MaterialPageRoute(
builder: (context) => ArticlePage(
article: article,
)));
},
child: Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 3.0,
),
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
article.urlToImage != null
? Container(
height: 200.0,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(article.urlToImage),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(12.0),
),
)
: Container(
height: 200.0,
width: double.infinity,
child: Image.network('https://picsum.photos/250?image=9'),
),
SizedBox(height: 8.0),
Container(
padding: EdgeInsets.all(6.0),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(30.0),
),
child: Text(
article.source.name,
style: TextStyle(
color: Colors.white,
),
),
),
SizedBox(height: 8.0),
Text(
article.title,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
)
],
),
),
);
}
You do not have access to a BuildContext. The quick solution, pass context to the customListTile method like so:
Widget customListTile(BuildContext context, Article article)
However, the best design practice would be to make a CustomListTile class that extends a StatelessWidget or a StatefulWidget rather than a function. Then you will have access to the BuildContext within the widget.

How to generate new route to the new stfull widget when user created new container?

I am currently developing an app which people can save their receipt in it, I shared home screen below,initial time It will be empty, as soon as user add new menu, it will get full with menu, After user added new menu, the should be able to click the menu container, and access to new screen for example, İn home screen I created container which called "CAKES", the cakes screen should be created, if I created another menu in my home screen It should also created too, I currently menu extanded screen as a statefull widget already, you can see below, but my question is How can I create this page for spesific menu's , How can I store them, in list, in map etc, Lastly, I dont want user information dissapear, I know I have to use database, but I want to use local database, How can I handle with that, Have a nice day...
import 'package:flutter/material.dart';
import 'package:lezzet_kitabi/add_menu_screen.dart';
import 'package:lezzet_kitabi/constants.dart';
import 'package:lezzet_kitabi/widgets.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({this.newMenuName,this.imagePath});
final imagePath;
final newMenuName;
static String id="homeScreen";
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Menü Ekle",route: HomeScreen,);
void initState(){
super.initState();
if (widget.newMenuName!=null && widget.imagePath!=null){
Widget newMenu=MenuCard(newMenuName: widget.newMenuName,imagePath: widget.imagePath);
menuCards.insert(0,newMenu);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: kColorTheme1,
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:TitleBorderedText(title:"SEVIMLI YEMEKLER", textColor: Color(0xFFFFFB00)),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage(kCuttedLogoPath),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(kBGWithLogoOpacity),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route: "homeScreen",),
);
},
child: TitleBorderedText(title: "LEZZET GRUBU EKLE",textColor: Colors.white,)
),
),
),
],
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:lezzet_kitabi/screens/home_screen.dart';
import 'package:lezzet_kitabi/widgets.dart';
import 'constants.dart';
import 'dart:math';
class AddMenuScreen extends StatefulWidget {
AddMenuScreen({#required this.buttonText, #required this.route});
final route;
final String buttonText;
static String id="addMenuScreen";
#override
_AddMenuScreenState createState() => _AddMenuScreenState();
}
class _AddMenuScreenState extends State<AddMenuScreen> {
int selectedIndex=-1;
Color _containerForStickersInactiveColor=Colors.white;
Color _containerForStickersActiveColor=Colors.black12;
final stickerList= List<String>.generate(23, (index) => "images/sticker$index");
String chosenImagePath;
String menuName;
int addScreenImageNum;
void initState(){
super.initState();
createAddScreenImageNum();
}
void createAddScreenImageNum(){
Random random =Random();
addScreenImageNum = random.nextInt(3)+1;
}
#override
Widget build(BuildContext context) {
return Material(
child: Container(
color: kColorTheme9,
child: Container(
height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
),
child:Padding(
padding:EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: kColorTheme2,
borderRadius: BorderRadius.circular(90)
),
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"Graduate",
fontSize: 20,
),
textAlign: TextAlign.center,
onChanged: (value){
menuName=value;
},
decoration: InputDecoration(
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: Colors.teal,
),
),
hintText: "Menü ismi belirleyin",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.2),
fontFamily: "Graduate",
),
),
),
),
SizedBox(height: 20,),
Text(" yana kadırarak menünüz icin bir resim secin",textAlign: TextAlign.center,
style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
SizedBox(height: 20,),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: stickerList.length,
itemBuilder: (context,index){
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: index == selectedIndex ?
_containerForStickersActiveColor :
_containerForStickersInactiveColor,
),
child:FlatButton(
child: Image(
image: AssetImage("images/sticker$index.png"),
),
onPressed: (){
setState(() {
selectedIndex = index;
});
},
),
);
}
),
),
SizedBox(height: 20,),
Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(90),
),
child: FlatButton(
onPressed: (){
widget.route=="homeScreen"?Navigator.push(context, MaterialPageRoute(builder: (context)=>HomeScreen(newMenuName: menuName,imagePath: "images/sticker$selectedIndex.png")))
:Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: menuName)),
);
},
child: Text(widget.buttonText, style: TextStyle(fontSize: 20, color: Colors.white,
fontFamily: "Graduate", fontWeight: FontWeight.bold),),
),
),
],
),
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'dart:math';
import 'add_menu_screen.dart';
import 'package:bordered_text/bordered_text.dart';
import 'package:lezzet_kitabi/screens/meal_screen.dart';
import 'constants.dart';
List<Widget> menuExtensionCards=[EmptyMenu()];
List<Widget> menuCards=[EmptyMenu()];
class MenuCard extends StatelessWidget {
MenuCard({this.newMenuName, this.imagePath});
final newMenuName;
final imagePath;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: newMenuName,)));
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(0.5),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 10,),
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.5),
borderRadius: BorderRadius.circular(90),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
newMenuName,
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Graduate',
fontWeight: FontWeight.bold),
),
),
),
Expanded(
child: Padding(
padding:EdgeInsets.all(5),
child: Image(
image: AssetImage(
imagePath
),
),
),
),
],
),
),
),
);
}
}
class EmptyMenu extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route:"homeScreen"),
);
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.black12.withOpacity(0.1),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.add_circle_outline_outlined,size: 100,color: Colors.grey.shade400,),
],
),
),
),
);
}
}
class MenuExtension extends StatefulWidget {
MenuExtension({this.menuExtensionName});
final String menuExtensionName;
#override
_MenuExtensionState createState() => _MenuExtensionState();
}
class _MenuExtensionState extends State<MenuExtension> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Tarif Ekle",route: MealScreen,);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:BorderedText(
child:Text(
widget.menuExtensionName,
style: TextStyle(
color: Color(0XFFFFFB00),
fontSize: 30,
fontFamily: "Graduate"
),
),
strokeWidth: 5,
strokeColor: Colors.black,
),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage("images/cuttedlogo.PNG"),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logoBGopacity.png"),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuExtensionCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Tarif Ekle", route:"mealScreen"),
);
},
child: BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text("Tarif Ekle",style: TextStyle(
color: Colors.white,
fontFamily:'Graduate',
fontSize:30,
),
),
),
),
),
),
],
)
],
),
),
),
);
}
}
class TitleBorderedText extends StatelessWidget {
TitleBorderedText({this.title, this.textColor});
final Color textColor;
final String title;
#override
Widget build(BuildContext context) {
return BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text(title,style: TextStyle(
color: textColor,
fontFamily:'Graduate',
fontSize:30,
),
),
);
}
}

How to go to a specific page using the button? Flutter

I create Welcome Page, when clicking the button I would like the user to be redirected to the home page, but when I click it gives several errors. I don't know how to program very well in flutter, can someone help me?
I tried in many ways, and they all fail. If you have to press the button to restart the APP it would also work, but I don't know how to solve it in any way
WELCOME PAGE (I would like to be redirected to HOME by clicking the button)
import 'package:flutter/material.dart';
import '../../main.dart';
import '../models/items.dart';
import '../helpers/helper.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/cupertino.dart';
void main() => runApp(Welcome());
Future<void> Return() async {
runApp(MyApp());
}
class Welcome extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: WelcomeScreen(),
);
}
}
class WelcomeScreen extends StatefulWidget {
final GlobalKey<ScaffoldState> parentScaffoldKey;
WelcomeScreen({Key key, this.parentScaffoldKey}) : super(key: key);
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
List<Widget> slides = items
.map((item) => Container(
padding: EdgeInsets.symmetric(horizontal: 18.0),
child: Column(
children: <Widget>[
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Image.asset(
item['image'],
fit: BoxFit.fitWidth,
width: 220.0,
alignment: Alignment.bottomCenter,
),
),
Flexible(
flex: 1,
fit: FlexFit.tight,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 30.0),
child: Column(
children: <Widget>[
Text(item['header'],
style: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.w300,
color: Color(0XFF3F3D56),
height: 2.0)),
Text(
item['description'],
style: TextStyle(
color: Colors.grey,
letterSpacing: 1.2,
fontSize: 16.0,
height: 1.3),
textAlign: TextAlign.center,
)
],
),
),
)
],
)))
.toList();
double currentPage = 0.0;
final _pageViewController = new PageController();
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: Helper.of(context).onWillPop,
child: Scaffold(
body: Stack(
alignment: AlignmentDirectional.topCenter,
children: <Widget>[
PageView.builder(
controller: _pageViewController,
itemCount: slides.length,
itemBuilder: (BuildContext context, int index) {
_pageViewController.addListener(() {
setState(() {
currentPage = _pageViewController.page;
});
});
return slides[index];
},
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: EdgeInsets.only(top: 70.0),
padding: EdgeInsets.symmetric(vertical: 40.0),
)
),
Positioned(
bottom: 10,
child: RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context){
return HomeWidget();
},
highlightElevation: 2,
splashColor: Color(0xFF2F4565),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
padding: EdgeInsets.symmetric(horizontal: 40),
color: Color(0XFFEA5C44),
child: Text(
"Permitir",
style: TextStyle(color: Colors.white),
),
),
)
],
),
),
);
}
}
HOMEPAGE (I would like to be redirected to that page by clicking the button on the WELCOME page)
import 'package:flutter/material.dart';
import 'package:mvc_pattern/mvc_pattern.dart';
import '../../generated/l10n.dart';
import '../controllers/home_controller.dart';
import '../elements/CardsCarouselWidget.dart';
import '../elements/CaregoriesCarouselWidget.dart';
import '../elements/DeliveryAddressBottomSheetWidget.dart';
import '../elements/GridWidget.dart';
import '../elements/ProductsCarouselWidget.dart';
import '../elements/ReviewsListWidget.dart';
import '../elements/SearchBarWidget.dart';
import '../elements/ShoppingCartButtonWidget.dart';
import '../repository/settings_repository.dart' as settingsRepo;
import '../repository/user_repository.dart';
class HomeWidget extends StatefulWidget {
final GlobalKey<ScaffoldState> parentScaffoldKey;
HomeWidget({Key key, this.parentScaffoldKey}) : super(key: key);
#override
_HomeWidgetState createState() => _HomeWidgetState();
}
class _HomeWidgetState extends StateMVC<HomeWidget> {
HomeController _con;
#override
_HomeWidgetState() : super(HomeController()) {
_con = controller;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: new IconButton(
icon: new Icon(Icons.sort, color: Theme.of(context).hintColor),
onPressed: () => widget.parentScaffoldKey.currentState.openDrawer(),
),
automaticallyImplyLeading: false,
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: ValueListenableBuilder(
valueListenable: settingsRepo.setting,
builder: (context, value, child) {
return Text(
value.appName ?? S.of(context).home,
style: Theme.of(context).textTheme.headline6.merge(TextStyle(letterSpacing: 1.3)),
);
},
),
actions: <Widget>[
new ShoppingCartButtonWidget(iconColor: Theme.of(context).hintColor, labelColor: Theme.of(context).accentColor),
],
),
body: RefreshIndicator(
onRefresh: _con.refreshHome,
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: SearchBarWidget(
onClickFilter: (event) {
widget.parentScaffoldKey.currentState.openEndDrawer();
},
),
),
Padding(
padding: const EdgeInsets.only(top: 15, left: 20, right: 20),
child: ListTile(
dense: true,
contentPadding: EdgeInsets.symmetric(vertical: 0),
leading: Icon(
Icons.stars,
color: Theme.of(context).hintColor,
),
trailing: IconButton(
onPressed: () {
if (currentUser.value.apiToken == null) {
_con.requestForCurrentLocation(context);
} else {
var bottomSheetController = widget.parentScaffoldKey.currentState.showBottomSheet(
(context) => DeliveryAddressBottomSheetWidget(scaffoldKey: widget.parentScaffoldKey),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
),
);
bottomSheetController.closed.then((value) {
_con.refreshHome();
});
}
},
icon: Icon(
Icons.my_location,
color: Theme.of(context).hintColor,
),
),
title: Text(
S.of(context).top_markets,
style: Theme.of(context).textTheme.headline4,
),
subtitle: Text(
S.of(context).near_to + " " + (settingsRepo.deliveryAddress.value?.address ?? S.of(context).unknown),
style: Theme.of(context).textTheme.caption,
),
),
),
CardsCarouselWidget(marketsList: _con.topMarkets, heroTag: 'home_top_markets'),
ListTile(
dense: true,
contentPadding: EdgeInsets.symmetric(horizontal: 20),
leading: Icon(
Icons.trending_up,
color: Theme.of(context).hintColor,
),
title: Text(
S.of(context).trending_this_week,
style: Theme.of(context).textTheme.headline4,
),
subtitle: Text(
S.of(context).clickOnTheProductToGetMoreDetailsAboutIt,
maxLines: 2,
style: Theme.of(context).textTheme.caption,
),
),
ProductsCarouselWidget(productsList: _con.trendingProducts, heroTag: 'home_product_carousel'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: ListTile(
dense: true,
contentPadding: EdgeInsets.symmetric(vertical: 0),
leading: Icon(
Icons.category,
color: Theme.of(context).hintColor,
),
title: Text(
S.of(context).product_categories,
style: Theme.of(context).textTheme.headline4,
),
),
),
CategoriesCarouselWidget(
categories: _con.categories,
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
child: ListTile(
dense: true,
contentPadding: EdgeInsets.symmetric(vertical: 0),
leading: Icon(
Icons.trending_up,
color: Theme.of(context).hintColor,
),
title: Text(
S.of(context).most_popular,
style: Theme.of(context).textTheme.headline4,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GridWidget(
marketsList: _con.popularMarkets,
heroTag: 'home_markets',
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: ListTile(
dense: true,
contentPadding: EdgeInsets.symmetric(vertical: 20),
leading: Icon(
Icons.recent_actors,
color: Theme.of(context).hintColor,
),
title: Text(
S.of(context).recent_reviews,
style: Theme.of(context).textTheme.headline4,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: ReviewsListWidget(reviewsList: _con.recentReviews),
),
],
),
),
),
);
}
}
First you need to set up the route:
MaterialApp(
// Start the app with the "/" named route. In this case, the app starts
// on the FirstScreen widget.
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => FirstScreen(), //NOTE: Change the FirstScreen() to your own screen's class name (ex: WelcomeScreen())
// When navigating to the "/second" route, build the SecondScreen widget.
'/second': (context) => SecondScreen(), //NOTE: Change the SecondScreen() to your own screen's class name (ex: HomeWidget())
'/third': (context) => ThirdScreen(),
},
);
And then, inside your button, navigate to the page:
// Within the `FirstScreen` widget
onPressed: () {
// Navigate to the second screen using a named route.
Navigator.pushNamed(context, '/second');
}
NOTE: One of your pages must be named as / to prevent error, for the full tutorial please visit this link

Acessing List items on another class

Hi I would like to know how can I access the items of a list on a different class where the list was created.Particularly i want to access items of the restaurantList on the Restaurant Screen class.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/models/restaurant.dart';
List<Restaurant> restaurantList=[
Restaurant(image:"kfcloja.jpg",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
Restaurant(image:"dominos.jpg",distance: "0.9 miles away",location:"Downtown",restaurantName: "Dominos"),
Restaurant(image:"kfclogo.png",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
];//I would like to access the items on the list
class RestaurantWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 350,
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: restaurantList.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: 1.0,
color: Colors.grey[100]
),
borderRadius: BorderRadius.circular(20)
),
child: Row(
children: <Widget>[
Container(
width: 150,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.asset("images/${restaurantList[index].image}",fit:BoxFit.cover ,)
)
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Container(
padding: EdgeInsets.all(2),
height: 70,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("${restaurantList[index].restaurantName}",style: TextStyle(fontWeight: FontWeight.bold),),
Row(
children: <Widget>[
Icon(Icons.star,size: 15,color:Colors.yellowAccent,),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star,size: 15,color:Colors.yellowAccent),
Icon(Icons.star_half,size: 15,color:Colors.yellowAccent),
],
),
Text("${restaurantList[index].location}"),
Text("${restaurantList[index].distance}"),
],
),
),
),
],
),
),
);
},
),
);
}
}
In this class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/widgets/menu_widget.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
class RestaurantScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: 400,
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Image.asset(
"images/kfcloja.jpg",
fit: BoxFit.cover,
),
Positioned(
child: IconButton(
icon: Icon(Icons.keyboard_arrow_left,size: 40,color: Colors.white,),
onPressed: (){},
),
top: 15,
)
],
),
Padding(
padding: const EdgeInsets.only(top: 14, left: 14, right: 14),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Restaurant KFC",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
Text(
"0.2 miles away",
style: TextStyle(
fontSize: 16,
),
),
],
),
Align(
alignment: Alignment.topLeft,
child: SmoothStarRating(
allowHalfRating: false,
starCount: 5,
size: 20.0,
filledIconData: Icons.blur_off,
halfFilledIconData: Icons.blur_on,
color: Colors.yellowAccent,
borderColor: Colors.yellowAccent,
spacing: 0.0),
),
Align(
alignment: Alignment.topLeft,
child: Text("200 Main St, New york"),
),
Padding(
padding: const EdgeInsets.only(
left: 30, right: 30, top: 20, bottom: 5),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton.icon(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
),
color: Theme.of(context).primaryColor,
icon: Icon(
Icons.rate_review,
color: Colors.white,
),
label: Text(
'Reviews',
style: TextStyle(color: Colors.white),
),
onPressed: () {},
),
FlatButton.icon(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
),
color: Theme.of(context).primaryColor,
icon: Icon(
Icons.contact_phone,
color: Colors.white,
),
label: Text(
'Contact',
style: TextStyle(color: Colors.white),
),
onPressed: () {},
)
],
),
),
),
Text(
"Menu",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
),
MenuWidget(),
],
)
),
)
],
),
),
);
}
}
You can send and receive the data from one screen to another as follow , you need to use the Navigator for it , In below example i am sending the data from class A to class B as follow
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => B(bean: restaurantList[index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
);
And inside the B class you need to create the contrsutor to receive the data from A like below
class B extends StatefulWidget {
Restaurant bean;
B ({Key key, #required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean"
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _B();
}
}
And please check the example of it to pass data from one class to another
A class which send data to B class
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'B.dart';
import 'Fields.dart';
class A extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _A();
}
}
class _A extends State<A> {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Screen A',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.red,
accentColor: Color(0xFFFEF9EB),
),
home: Scaffold(
appBar: new AppBar(),
body: Container(
margin: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: Text("Screen A"),
),
Expanded(
child: ListView.builder(
itemCount: fields.length,
itemBuilder: (BuildContext ctxt, int index) {
return ListTile(
title: new Text("Rating #${fields[index].rating}"),
subtitle: new Text(fields[index].title),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => B(bean: fields [index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
);
},
);
}),
)
],
),
)));
}
}
List<Fields> fields = [
new Fields(
'One',
1,
),
new Fields(
'Two',
2,
),
new Fields(
'Three',
3,
),
new Fields(
'Four',
4,
),
new Fields(
'Five',
5,
),
];
Now check B class which receive the data from A class
import 'package:flutter/material.dart';
import 'Fields.dart';
class B extends StatefulWidget{
Fields bean;
B ({Key key, #required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean"
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _B ();
}
}
class _B extends State<B> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Screen A',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.red,
accentColor: Color(0xFFFEF9EB),
),
home: Scaffold(
appBar: new AppBar(),
body: Container(
margin: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text("Screen B" ,style: TextStyle(fontSize: 20.0),),
)
),
Text("Rating=>>> ${widget.bean.rating} and Title ${widget.bean.title} ")
],
),
)));
}
}
And I have used the Pojo class for the list ,please check it once
Fields.dart
class Fields {
final String title;
final int rating;
Fields(this.title, this.rating);
}
And the output of the above program as follow.