After Scanning Barcode , how to pass scanned data to a new page? - flutter

the thing I will like to ask about is that I want to pass the data in the barcode to a new page after scanning. Is there anyway can I do it?
Hope anyone can solve my problem <3
Had been doing this for my intern for 4 days and I have no clue at all. Hope can solve it as fast as possible
Below is my code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:meditation_app/widgets/category_card.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String _scanBarcode = 'Unknown';
#override
void initState() {
super.initState();
}
Future<void> scanBarcodeNormal() async {
String barcodeScanRes ;
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes; //Here is the thing I will like to pass to another page
});
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('EzyMerchant'),
actions: <Widget>[
IconButton(
icon: SvgPicture.asset("assets/icons/setting.svg",color: Colors.white,),
onPressed: () {
Navigator.pushNamed(context, '/setting');
},
),
],
),
body: Stack(
children: <Widget>[
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical:20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Good Morning \nAdmin",
style: Theme.of(context)
.textTheme
.headline4
.copyWith(fontWeight: FontWeight.w900),
),
SizedBox(height: 50),
Expanded(
child: Container(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: .85,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
children: <Widget>[
Container(
child: CategoryCard(
title: "Add",
svgSrc: ("assets/icons/Hamburger.svg"),
press: () => scanBarcodeNormal(), //Here is the scan function
),
),
CategoryCard(
title: "Redeem",
svgSrc: "assets/icons/Excrecises.svg",
press: () {},
),
CategoryCard(
title: "Wallet",
svgSrc: "assets/icons/Meditation.svg",
press: () {},
),
CategoryCard(
title: "Voucher",
svgSrc: "assets/icons/yoga.svg",
press: () {},
),
],
),
),
),
],
),
),
)
],
),
);
}
}

You can use arguments property in Navigator.pushNamed like
Navigator.pushNamed(context, '/setting',arguments: _scanBarcode);

Related

Display Widget onPressed button Flutter

My goal is to display certain widgets based on clicks in a menu.
What I need when I click a title, is to shows a certain widget.
Here is the full code:
class SideMenu extends StatelessWidget {
const SideMenu({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Drawer(
child: SingleChildScrollView(
// it enables scrolling
child: Column(
children: [
DrawerHeader(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: defaultPadding * 3,
),
Image.asset(
"assets/logo/logo_icon.png",
scale: 5,
),
SizedBox(
height: defaultPadding,
),
Text("Récolt"),
],
)),
DrawerListTile(
title: "Tableau de bord",
svgSrc: "assets/icons/menu_dashbord.svg",
press: () {},
),
DrawerListTile(
title: "Utilisateurs",
svgSrc: "assets/icons/menu_profile.svg",
press: () {},
),
DrawerListTile(
title: "Collaborateurs",
svgSrc: "assets/icons/menu_doc.svg",
press: () {},
),
DrawerListTile(
title: "Producteurs",
svgSrc: "assets/icons/menu_store.svg",
press: () {},
),
DrawerListTile(
title: "Paramètres",
svgSrc: "assets/icons/menu_setting.svg",
press: () {},
),
],
),
),
);
}
}
I've got a extern page for display my widget like this :
SizedBox(height: defaultPadding),
ListUserEntreprise(),
SizedBox(height: defaultPadding),
ListUserCollab(),
I don't know how to do it, I tried with using a boolean in onPressed but it didn't work, I don't know really how to declare it and use it with an external page. Can someone help me, please?
use StatefulWidget and try with a boolean with the onPressed, setState() to update UI
Example:
import 'package:flutter/material.dart';
class SideMenu extends StatefulWidget {
const SideMenu({
Key? key,
}) : super(key: key);
#override
State<SideMenu> createState() => _SideMenuState();
}
class _SideMenuState extends State<SideMenu> {
bool _isShow = false;
#override
Widget build(BuildContext context) {
return Drawer(
child: SingleChildScrollView(
// it enables scrolling
child: Column(
children: [
DrawerListTile(
title: "Tableau de bord",
svgSrc: "assets/icons/menu_dashbord.svg",
press: () {
setState(() {
_isShow = !_isShow;
});
},
),
Visibility(
visible: _isShow,
child: Container(
child: Text('Tableau de bord'),
))
],
),
),
);
}
}

i can't see my images on carousel slider before i hot reload

hello everyone i am new in flutter. i have a problem, when i start the application i cant see my images on carousel but when i hot reload i can see them. I think that if i put if/else condition it might work but i could not do it can some one help me about that?
here are the codes;
import 'dart:convert';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:feedme_start/widgets/Navigation_Drawer_Widget.dart';
import 'package:flutter/material.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:http/http.dart';
import 'model/AnaEkran_modeli.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
final imageList = [];
int ct = imageList.length;
class _MyAppState extends State<MyApp> {
String cevap = "";
late Apianaekran _apianaekran;
late Result _result;
get Index => null;
//"getapidata" adlı future methodda apilerle resimleri çekiyorum sonra imageListe ekliyorum
Future<void> getapidata() async {
String url =
"https://www.mobilonsoft.com/fpsapi/default.aspx?op=application_initialization_customer&firmuid=feedmekktc&device_id=web_20210813180900001&device_platform=4&lang=en";
Response responsee = await get(Uri.parse(url));
if (responsee.statusCode == 200) {
//statusCode 200 oldumu bağlantı siteyle doğru şekilde kuruldu demektir.
Map cevapjson =
jsonDecode(responsee.body); //cevap, json code daki body i alır.
Apianaekran ekran = Apianaekran.fromJson(cevapjson);
ct = ekran.result.sliderImages.length;
print(ct);
int i = 0;
while (i < ct) {
imageList.add(ekran.result.sliderImages[i].imageUrl);
print(ekran.result.sliderImages[i].imageUrl);
i++;
}
} else {
print("bir sorun oluştu");
}
print("resimler başarıyla çekildi");
print(imageList.length);
}
#override
void initState() {
getapidata();
}
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.red,
title: Center(child: Text("FEED ME")),
actions: <Widget>[
IconButton(onPressed: () {}, icon: Icon(Icons.call))
],
),
drawer: NavigationDrawerWidget(),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Column(
children: [
Container(
constraints: BoxConstraints.expand(height: 200),
child: CarouselSlider(
options: CarouselOptions(
enlargeCenterPage: true,
enableInfiniteScroll: true,
autoPlay: true),
items: imageList
.map((e) => ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.network(
e,
width: 1050,
height: 350,
fit: BoxFit.cover,
)
],
),
))
.toList())), //imageSlider(context),),
/* Divider(,,
color: Colors.red,
),*/
SizedBox(
height: 75,
),
ElevatedButton.icon(
onPressed: () {
getapidata();
}, //api çekiminin denemesini bu tuşnan yaparım şimdilik
icon: Icon(Icons.add),
label: Text("Yeni Sipariş Ver"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red)),
),
SizedBox(
height: 50,
),
// Text(_anaEkranJsonlar.statusCodeDescription),
SizedBox(
height: 150,
),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.add),
label: Text("Canlı Destek"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
SizedBox(
width: 5,
),
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.sms),
label: Text("Fırsatlar"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
],
),
SizedBox(
height: 30,
),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.exit_to_app),
label: Text("Giriş"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
SizedBox(
width: 5,
),
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.person_add),
label: Text("Kayıt Ol"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
],
)
],
),
)
/*Swiper(itemCount: imageList.length,
itemBuilder: (context, index) {
return Image.network(imageList[index],/*errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace), {return const("resim yüklenemedi")},*/
fit: BoxFit.cover,);
},)*/
),
);
}
}
this is the picture of first start
this one is after i hot reload the code
it has to be like in 2nd pic. can someone help me ?
You need to update the state of your widget inside getapidata after you've loaded all the images:
Future<void> getapidata() async {
String url = "https://www.mobilonsoft.com/fpsapi/default.aspx?op=application_initialization_customer&firmuid=feedmekktc&device_id=web_20210813180900001&device_platform=4&lang=en";
Response responsee = await get(Uri.parse(url));
if (responsee.statusCode == 200) {
// ...
setState(() {});
}
}
The above will already work as expected, but you should consider using a FutureBuilder. Also, you should put
final imageList = [];
int ct = imageList.length;
inside your widget's state, and not in the global scope.

flutter Problem: How to update number of items count in cart?

I implement to add to cart functionality items added into cart successfully but the number of count in the cart badge is not updated when I reload dart page than the number of count updates.can anyone help me?
I implement to add to cart functionality items added into cart successfully but the number of count in the cart badge is not updated when I reload dart page than the number of count updates.can anyone help me?
This is my Homepage.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:badges/badges.dart';
import 'package:hospital/BestDeatProducts/best_deal_product_page.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/FirstSection/carousel.dart';
import 'package:hospital/Drawer/drawercontent.dart';
import 'package:hospital/FloatingActionButton/ConsultWithDoctor/consult_with_doctor.dart';
import 'package:hospital/MedicineCateory/medicine_category_page.dart';
import 'package:hospital/SecondSection/second_page.dart';
import 'package:hospital/ThirdSection/third_page.dart';
import 'package:hospital/TrendingProducts/trending_product_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'No Internet/connectivity_provider.dart';
import 'No Internet/no_internet.dart';
import 'package:http/http.dart' as http;
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
SharedPreferences loginData;
// late String username;
Future getUsername() async {
loginData = await SharedPreferences.getInstance();
setState(() {
// print("uname" + uname.toString());
print("dddpppuu1 : responceData_un" +
loginData.getString('responceData_un').toString());
print("dddpppuu2 : responceData_ue" +
loginData.getString('responceData_ue').toString());
print("dddpppuu3 : responceData_status" +
loginData.getString('responceData_status').toString());
String responceData_uid =
loginData.getString('responceData_uid').toString();
fetchData(responceData_uid);
});
}
var response;
var addToCartApi;
#override
void initState() {
// TODO: implement initState
//
super.initState();
Provider.of<ConnectivityProvider>(context, listen: false).startMonitering();
// for loading
getUsername();
}
fetchData(String argResponceData_uid) async {
var api = Uri.parse(
'$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${argResponceData_uid}');
print('cartpage' + api.toString());
response = await http.get(api);
print("Carousel" + response.body);
addToCartApi = jsonDecode(response.body);
print('addToCartApi' + addToCartApi['total'].toString());
print('totalPriceAfterOffer' + totalPriceAfterOffer.toString());
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: kGreen,
title: Text(
"BK Arogyam",
style: TextStyle(fontStyle: FontStyle.italic),
),
actions: [
response != null
? Badge(
position: BadgePosition.topEnd(top: 3, end: 18),
animationDuration: Duration(milliseconds: 300),
animationType: BadgeAnimationType.slide,
badgeContent: Text(
addToCartApi['total']['num'].toString(),
style: TextStyle(color: Colors.white),
),
child: IconButton(
icon: Icon(Icons.shopping_cart),
padding: EdgeInsets.only(right: 30.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Cartpage()),
);
}),
)
: IconButton(
icon: Icon(Icons.shopping_cart),
// onPressed: () => print("open cart"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Cartpage()),
);
},
),
DropDownMenu(),
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: kGreen,
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => ConsultWithDoctor())),
tooltip: 'Consult With Doctor',
child: Container(
child: Image(
image: AssetImage(
"assets/icons/cwd.png",
),
color: Colors.white,
width: 40,
height: 40,
),
),
),
drawer: Drawer(
child: DrawerContent(),
),
body: pageUI());
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (consumerContext, model, child) {
if (model.isOnline != null) {
return model.isOnline
? ListView(
children: [
Carousel(),
SizedBox(
height: 10.0,
),
MedicineCategoryPage(),
SizedBox(
height: 10.0,
),
SecondPage(),
SizedBox(
height: 10.0,
),
ThirdPage(),
SizedBox(
height: 10.0,
),
TrendingProductPage(),
SizedBox(
height: 16.0,
),
BestDealProductPage(),
SizedBox(
height: 10.0,
),
],
)
: NoInternet();
}
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
},
);
}
}
You can use the change notifier provide by provider package.
And watch the video on how to use, exactly for ur use case search YouTube change notifier provider by the growing developer
Hope it helps 🙂
You can use provider(provider: ^5.0.0) or Getx(get: ^4.1.4) to handle this kind of case.
There are lots of examples are available for GetX and Provider.
If you don't want to use any of them, Then store your cart/badge count to tempCartCount variable(Example: int cartCount = 0) and set it to the badge count instead of "addToCartApi['total']['num'].toString()" , Make sure to setState on update/addCart Item.
Here I provide a simple example of how to update count on appBar.
if you want to change from any other screen make cartCount to global otherwise you can set it local/private.
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
class UpdateCountExample extends StatefulWidget {
#override
_UpdateCountExampleState createState() => _UpdateCountExampleState();
}
int cartCount = 0;
class _UpdateCountExampleState extends State<UpdateCountExample> {
List<String> cartArray = [];
#override
void initState() {
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
setState(() {
cartCount = 0;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("App Bar"),
actions: [
Padding(
padding: const EdgeInsets.only(right: 18.0, top: 5.0),
child: Badge(
badgeContent: Text(cartCount.toString()),
child: Icon(Icons.add_shopping_cart),
),
)
],
),
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Add item in cart",
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, decoration: TextDecoration.none, color: Colors.black),
),
SizedBox(
height: 20,
),
InkWell(
onTap: () {
setState(() {
cartArray.add("value ${cartArray.length}");
cartCount = cartArray.length;
});
},
child: Container(
padding: const EdgeInsets.all(10.0),
color: Colors.amber,
child: Text(
"Add Item",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, decoration: TextDecoration.none, color: Colors.black),
),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: cartArray.length,
itemBuilder: (context, index) {
return Text(
cartArray[index],
style: TextStyle(fontSize: 20, color: Colors.black),
);
}),
)
],
),
),
);
}
}
I have used StreamBuilder to update cart items instantly.
You can use the code from this post
How to use Streambuilder in flutter

Why isn't Navigator.pop() refreshing data?

Hi guys I'm trying to build an app with flutter, so I have two screens HomeScreen() and RoutineScreen(). The first one is a Scaffold and in the body has a child Widget (a ListView called RoutinesWidget()) with all the routines. And the second one is to create a routine. The thing is, that when I create the routine, I use a button to pop to the HomeScreen() but it doesn't refresh the ListView (I'm guessing that it's because when I use Navigator.pop() it refreshes the Scaffold but not the child Widget maybe?)
HomeScreen() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Widgets/routines_widget.dart';
import 'package:workout_time/Widgets/statistics_widget.dart';
import 'package:workout_time/Screens/settings_screen.dart';
import 'package:workout_time/Screens/routine_screen.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
List<Widget> _views = [
RoutinesWidget(),
StatisticsWidget(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: kThirdColor,
appBar: AppBar(
leading: Icon(Icons.adb),
title: Text("Workout Time"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.settings),
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => SettingsScreen()))),
],
),
body: _views[_selectedIndex],
floatingActionButton: (_selectedIndex == 1)
? null
: FloatingActionButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RoutineScreen(null)));
setState(() {});
},
child: Icon(
Icons.add,
color: kSecondColor,
size: 30.0,
),
elevation: 15.0,
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
bottomItems(Icon(Icons.fitness_center_rounded), "Routines"),
bottomItems(Icon(Icons.leaderboard_rounded), "Statistics"),
],
currentIndex: _selectedIndex,
onTap: (int index) => setState(() => _selectedIndex = index),
),
);
}
}
BottomNavigationBarItem bottomItems(Icon icon, String label) {
return BottomNavigationBarItem(
icon: icon,
label: label,
);
}
RoutinesWidget() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/Services/db_crud_service.dart';
import 'package:workout_time/Screens/routine_screen.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Models/routine_model.dart';
class RoutinesWidget extends StatefulWidget {
#override
_RoutinesWidgetState createState() => _RoutinesWidgetState();
}
class _RoutinesWidgetState extends State<RoutinesWidget> {
DBCRUDService helper;
#override
void initState() {
super.initState();
helper = DBCRUDService();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: helper.getRoutines(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Routine routine = Routine.fromMap(snapshot.data[index]);
return Card(
margin: EdgeInsets.all(1.0),
child: ListTile(
leading: CircleAvatar(
child: Text(
routine.name[0],
style: TextStyle(
color: kThirdOppositeColor,
fontWeight: FontWeight.bold),
),
backgroundColor: kAccentColor,
),
title: Text(routine.name),
subtitle: Text(routine.exercises.join(",")),
trailing: IconButton(
icon: Icon(Icons.delete_rounded),
color: Colors.redAccent,
onPressed: () {
setState(() {
helper.deleteRoutine(routine.id);
});
},
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RoutineScreen(routine))),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
color: kSecondColor,
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
}
RoutineScreen() code here:
import 'package:flutter/material.dart';
import 'package:workout_time/Models/routine_model.dart';
import 'package:workout_time/Widgets/type_card_widget.dart';
import 'package:workout_time/constants.dart';
import 'package:workout_time/Services/db_crud_service.dart';
class RoutineScreen extends StatefulWidget {
final Routine _routine;
RoutineScreen(this._routine);
#override
_RoutineScreenState createState() => _RoutineScreenState();
}
class _RoutineScreenState extends State<RoutineScreen> {
DBCRUDService helper;
final _nameController = TextEditingController();
final _descriptionController = TextEditingController();
bool _type = true;
int _cycles = 1;
int _restBetweenExercises = 15;
int _restBetweenCycles = 60;
#override
void initState() {
super.initState();
helper = DBCRUDService();
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context),
),
title: widget._routine != null
? Text(widget._routine.name)
: Text("Create your routine"),
actions: [
IconButton(
icon: Icon(Icons.done_rounded),
onPressed: createRoutine,
)
],
bottom: TabBar(
tabs: [
Tab(
text: "Configuration",
),
Tab(
text: "Exercises",
),
],
),
),
body: TabBarView(children: [
//_routine == null ? ConfigurationNewRoutine() : Text("WIDGET N° 1"),
ListView(
children: [
Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: [
Text(
"Name:",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 40.0,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
controller: _nameController,
),
),
],
),
),
SizedBox(
height: 20.0,
),
Card(
margin: EdgeInsets.all(15.0),
color: kSecondColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
padding: EdgeInsets.all(15.0),
child: Column(
children: [
Text(
"Type",
style: TextStyle(fontSize: 25.0),
),
Row(
children: [
Expanded(
child: TypeCard(
Icons.double_arrow_rounded,
_type == true ? kFirstColor : kThirdColor,
() => setState(() => _type = true),
"Straight set",
),
),
Expanded(
child: TypeCard(
Icons.replay_rounded,
_type == false ? kFirstColor : kThirdColor,
() => setState(() => _type = false),
"Cycle",
),
),
],
),
],
),
),
),
SizedBox(
height: 20.0,
),
Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: [
Text(
"N° cycles:",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 40.0,
),
Expanded(
child: Text("Hello"),
),
],
),
),
SizedBox(
height: 20.0,
),
],
),
Text("WIDGET N° 2"),
]),
),
);
}
void createRoutine() {
List<String> _exercises = ["1", "2"];
List<String> _types = ["t", "r"];
List<String> _quantities = ["30", "20"];
Routine routine = Routine({
'name': _nameController.text,
'description': "_description",
'type': _type.toString(),
'cycles': 1,
'numberExercises': 2,
'restBetweenExercises': 15,
'restBetweenCycles': 60,
'exercises': _exercises,
'types': _types,
'quantities': _quantities,
});
setState(() {
helper.createRoutine(routine);
Navigator.pop(context);
});
}
}
Any idea what can I do to make it work? Thank you
Make it simple
use Navigator.pop() twice
so that the current class and old class in also removed
from the stack
and then use Navigator.push()
When you push a new Route, the old one still stays in the stack. The new route just overlaps the old one and forms like a layer above the old one. Then when you pop the new route, it will just remove the layer(new route) and the old route will be displayed as it was before.
Now you must be aware the Navigator.push() is an asynchronous method and returns a Future. How it works is basically when you perform a Navigator.push(), it will push the new route and will wait for it to be popped out. Then when the new route is popped, it returns a value to the old one and that when the future callback will be executed.
Hence the solution you are looking for is add a future callback like this after your Navigator.push() :
Navigator.push(context,
MaterialPageRoute(builder: (context) => SettingsScreen())
).then((value){setState(() {});}); /// A callback which is executed after the new route will be popped. In that callback, you simply call a setState and refresh the page.

I want to pass data from 2nd Screen to 1st Screen in flutter

I am making a simple TODO app and I wanted to pass data from 2nd Screen of my app to 1st screen. My first Screen is initially blank and there is nothing to display and it has a floating button to add a task. When it is clicked it takes to the Second page where user inputs the task and author and Clicks on "Submit" Button and takes us to 1st page where it gets Displayed. I want to pass data as List .I am trying everything for last 24 hours I implemented using ModalRoute and also created one instance of ToDo class so that it doesn't give NULL error but nothing is working out. I am attaching code So that you can understand my problem.
This is my FirstScreen()
import 'package:flutter/material.dart';
import 'todo.dart';
import 'todocard.dart';
class ToDos extends StatefulWidget{
#override
_ToDosState createState() => _ToDosState();
}
class _ToDosState extends State<ToDos> {
#override
Widget build(BuildContext context) {
List<ToDo> todos =[
];
final routeArgs = ModalRoute.of(context).settings.arguments as Map ;
todos.add(ToDo(author: routeArgs['task'],task: routeArgs['author']));
return Container(
child: Scaffold(
appBar: AppBar(
title: Text("TODO LIST"),
centerTitle: true,
),
body: Column(
children:todos.map((e) => ToDoCard(
todo: e,
)).toList(),
//ToDoCard is just a Card widget
),
floatingActionButton: FloatingActionButton(
elevation: 0.0,
child: Text("+"),
onPressed: ()
{
Navigator.pushNamed(context, '/add_task');
},
),
),
);
}
}
My SecondScreen is :
import 'package:flutter/material.dart';
class AddTask extends StatefulWidget {
#override
_AddTaskState createState() => _AddTaskState();
}
class _AddTaskState extends State<AddTask> {
#override
Widget build(BuildContext context) {
String author,task;
return Container(
child: Scaffold(
appBar: AppBar(
title: Text("ADD TASK"),
centerTitle: true,
),
body: Column(
children: <Widget>[
Text("Enter Your Task"),
TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'task'
),
onChanged: (text){
task = text;
},
),
TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'author'
),
onChanged: (text){
author = text;
},
),
Row(
children: <Widget>[
RaisedButton(
onPressed: () {
Navigator.pop(context, {
'author': author,
'task': task,
});
},
child: Text("Submit"),
),
SizedBox(width: 10.0,),
RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Cancel"),
),
],
)
],
),
));
}
}
The main.dart is as Follows:
import 'package:flutter/material.dart';
import 'todo.dart';
import 'add_task.dart';
import 'display_todo.dart';
void main() {
runApp(MaterialApp(
title: 'Passing Data',
initialRoute: '/',
routes: {
'/': (context) => ToDos(),
'/add_task': (context) => AddTask(),
},
));
}
The ToDoCard for displaying the info as Card:
import 'todo.dart';
import 'package:flutter/material.dart';
class ToDoCard extends StatelessWidget {
final ToDo todo;
ToDoCard({this.todo});
#override
Widget build(BuildContext context) {
return Card(
color: Colors.cyan,
margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
child: Padding(
padding: EdgeInsets.fromLTRB(13, 10, 13, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
todo.author,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
SizedBox(height: 10.0,),
Text(
todo.task,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
SizedBox(height: 10.0,),
// RaisedButton.icon(onPressed: delete, icon: Icon(Icons.delete), label:
Text("Delete quote"), color: Colors.red,),
],
),
),
);
}
}
ToDo class:
class ToDo{
final String task;
final String author;
ToDo({this.task,this.author});
}
You can pass the result back on the Navigator.pop() and retrieve it by awaiting the pushNamed call.
Retrieve value in Page 1:
onPressed: () async
{
dynamic result = await Navigator.pushNamed(context, '/add_task');
if(result != null) {
setState(() {todos.add(result);});
}
},
Pass value from page 2 in the submit button
onPressed: () {
Navigator.pop(context, ToDo(task: task, author: author));
},