TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
showvalyxiong VANGTOUAXIONG
NA
6
1.6k
Flutter inherited widget inside ListView item
Nov 20 2019 10:26 PM
When i click qty plus on each item, Qty should plus on that item (But qty plus for all item)
who have good idea please help me please
thank you so much
inherited_widget.dart
import
'package:flutter/material.dart'
;
import
'inherited_widget_data.dart'
;
class
MyInheritedWidget
extends
InheritedWidget {
final
Widget child;
final
MyInheritedWidgetDataState state;
MyInheritedWidget({Key key,
@required
this
.child,
@required
this
.state})
:
super
(key: key, child: child);
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) {
return
true
;
}
}
inherited_widget_data.dart
import
'package:flutter/material.dart'
;
import 'inherited_widget.dart';
class
MyInheritedWidgetData
extends
StatefulWidget {
final
Widget child;
MyInheritedWidgetData({
@required
this
.child});
@override
MyInheritedWidgetDataState createState() => MyInheritedWidgetDataState();
static
MyInheritedWidgetDataState of(
[BuildContext context, bool rebuild =
true
]) {
return
(rebuild
? context.inheritFromWidgetOfExactType(MyInheritedWidget)
as MyInheritedWidget
: context.ancestorWidgetOfExactType(MyInheritedWidget)
as MyInheritedWidget)
.state;
}
}
class
MyInheritedWidgetDataState
extends
State<MyInheritedWidgetData> {
int
badgeNumer =
0
, qty =
1
, i =
0
;
@override
void
initState() {
super
.initState();
}
setbadgeNumer(
int
newbadgeNumer) {
setState(
() {
badgeNumer = newbadgeNumer;
},
);
}
setQty(
int
newQty) {
setState(
() {
qty += newQty;
i +=
1
;
},
);
}
@override
Widget build(BuildContext context) {
return
MyInheritedWidget(child: widget.child, state:
this
);
}
}
main.dart
//*******************Dart System package*******************
import
'dart:convert'
;
import
'dart:io'
;
import
'dart:typed_data'
;
import
'package:device_info/device_info.dart'
;
import
'package:flutter/material.dart'
;
//*******************pub.dev package*******************
import
'package:flutter_secure_storage/flutter_secure_storage.dart'
;
import
'package:get_ip/get_ip.dart'
;
import
'package:http/http.dart'
as http;
import
'package:carousel_slider/carousel_slider.dart'
as carouse;
//*******************Model package*******************
import
'mainpage/hometab/inherited_widget_data.dart'
;
import
'models/Viewproduct.dart'
;
import
'services/fn.dart'
;
//*******************Pages package*******************
void
main() => runApp(MyApp());
class
MyApp
extends
StatelessWidget {
@override
Widget build(BuildContext context) {
return
MaterialApp(
title:
'Flutter Demo'
,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
debugShowCheckedModeBanner:
false
,
);
}
}
class
HomePage
extends
StatefulWidget {
HomePage({Key key}) :
super
(key: key);
@override
_HomePageState createState() =>
new
_HomePageState();
}
class
_HomePageState
extends
State<HomePage>
with SingleTickerProviderStateMixin {
bool isBackButtonActivated =
false
;
//Event on page load
@override
void
initState() {
try
{
super
.initState();
_tabController = TabController(vsync:
this
, length: myTabs.length);
_tabController.addListener(() {
print(_tabController.index);
});
WidgetsBinding.instance.addPostFrameCallback((_) async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
Fn.deviceID = androidInfo.id;
Fn.deviceName = androidInfo.model;
Fn.ipaddress = await GetIp.ipAddress;
countrycode = await storage.read(key:
'countrycode'
) ??
"+856"
;
username = await storage.read(key:
'username'
);
loginResultID = await storage.read(key:
'loginResultID'
);
_refreshData();
//_asyncCheckAnotherLogin();
});
setState(() {});
}
catch
(e) {
print(e.toString());
}
}
//**************************** Variable for toolbar ****************************
static
String appName = Fn.company_name +
' \u00a9 2019'
;
Widget appBarTitle =
new
Text(appName);
Icon actionIcon =
new
Icon(Icons.search);
static
Color colorToolbar = Colors.deepOrange;
int
badgeNumer =
0
;
//**************************** Variable for login ****************************
String countrycode,
username,
password,
loginResultID =
""
,
isAnotherLoginResultID =
""
;
var txtusername = TextEditingController();
var txtpassword = TextEditingController();
final
txtusername_focus = FocusNode();
final
txtpassword_focus = FocusNode();
bool emailValid =
false
,
firstLoad =
true
,
isLogin =
false
,
password_visibility =
false
,
loadhometabeFail =
false
,
isAnotherLogin =
false
;
//**************************** Variable for home tabe ****************************
final
List<Tab> myTabs = <Tab>[
Tab(
icon: Icon(IconData(
0xe88a
, fontFamily:
'MaterialIcons'
)),
//text: 'Home',
),
Tab(
icon: Icon(
IconData(
57573
, fontFamily:
'MaterialIcons'
),
),
//text: 'Feed',
),
Tab(
icon: Icon(IconData(
59638
, fontFamily:
'MaterialIcons'
)),
//text: 'Promotion',
),
];
TabController _tabController;
ScrollController _scrollController;
final
GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new
GlobalKey<RefreshIndicatorState>();
final
storage =
new
FlutterSecureStorage();
List<RegViewproduct> homeTabdata;
Uint8List _bytes(String b64) {
try
{
return
base64.decode(b64);
}
catch
(e) {
print(e.toString());
}
}
Future<List<RegViewproduct>> _getData() async {
try
{
var photo = RegViewproduct();
//photo.albumId = '1';
String js = regViewproductToJson([photo]);
//print(js);
var rsp = await http.post(Fn.ihost.host +
'/sale/vw_product.php'
,
body: js,
headers: {HttpHeaders.contentTypeHeader:
'application/json'
});
//print(rsp.body);
return
regViewproductFromJson(rsp.body);
}
catch
(e) {
print(e.toString());
loadhometabeFail = e.toString() !=
null
;
}
}
Future<Null> _refreshData() {
try
{
return
_getData().then((onValue) {
//print(onValue);
setState(() {
homeTabdata = onValue;
});
});
}
catch
(e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return
MyInheritedWidgetData(
child: MaterialApp(
theme: ThemeData(
primarySwatch: colorToolbar,
//primaryColor: Colors.deepOrange, //Changing this will change the color of the TabBar
brightness: Brightness.light,
accentColor: Colors.green,
),
debugShowCheckedModeBanner:
false
,
home: DefaultTabController(
length:
1
,
child: WillPopScope(
onWillPop: () async =>
false
,
child: Scaffold(
appBar: AppBar(
centerTitle:
true
,
title: appBarTitle,
actions: <Widget>[
new
IconButton(
icon: actionIcon,
onPressed: () {
setState(() {
if
(
this
.actionIcon.icon == Icons.search) {
this
.actionIcon =
new
Icon(Icons.close);
this
.appBarTitle =
new
TextField(
autofocus:
true
,
style:
new
TextStyle(
color: Colors.white,
),
decoration:
new
InputDecoration(
prefixIcon:
new
Icon(Icons.search, color: Colors.white),
hintText:
'Search in '
+ Fn.company_name +
' ...'
,
hintStyle:
new
TextStyle(color: Colors.white),
),
);
}
else
{
this
.actionIcon =
new
Icon(Icons.search);
this
.appBarTitle =
new
Text(appName);
}
});
},
),
WidgetCartBadge(),
],
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
homeTabdata !=
null
? RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: _refreshData,
child: ListView(
controller: _scrollController,
children: <Widget>[
//************************* Image slider *************************
Container(
decoration:
const
BoxDecoration(
border: Border(
top: BorderSide(
width:
1.0
, color: Color(
0xFFFFFFFFFF
)),
left: BorderSide(
width:
1.0
, color: Color(
0xFFFFFFFFFF
)),
right: BorderSide(
width:
1.0
, color: Color(
0xFFFF000000
)),
bottom: BorderSide(
width:
5.0
,
color: Colors.grey,
),
),
),
child: Padding(
padding:
const
EdgeInsets.fromLTRB(
0
,
2
,
0
,
4
),
child: carouse.CarouselSlider(
height:
150.0
,
aspectRatio:
16
/
9
,
viewportFraction:
0.9
,
initialPage:
0
,
enableInfiniteScroll:
true
,
reverse:
false
,
autoPlay:
true
,
autoPlayInterval: Duration(seconds:
7
),
autoPlayAnimationDuration:
Duration(seconds:
3
),
//autoPlayCurve: Curve.fastOutSlowIn,
pauseAutoPlayOnTouch: Duration(seconds:
7
),
enlargeCenterPage:
true
,
//onPageChanged: callbackFunction,
scrollDirection: Axis.horizontal,
items: homeTabdata.map(
(i) {
return
Builder(
builder: (BuildContext context) {
return
Container(
alignment: Alignment.bottomCenter,
width: MediaQuery.of(context)
.size
.width,
margin: EdgeInsets.symmetric(
horizontal:
5.0
),
decoration: BoxDecoration(
image:
new
DecorationImage(
image: i.productImgBase64
.trim() !=
null
? MemoryImage(_bytes(i
.productImgBase64))
: Container(),
fit: BoxFit.cover),
color: Colors.amber),
child: Padding(
padding:
const
EdgeInsets.all(
8.0
),
child:
new
Text(
i.productBillName,
style:
new
TextStyle(
fontSize:
16.0
),
),
),
);
},
);
},
).toList(),
),
),
),
//************************* Product menu *************************
Container(
child: ListView(
shrinkWrap:
true
,
//crossAxisCount: 2,
physics: ScrollPhysics(),
children: homeTabdata
.getRange(
0
, homeTabdata.length)
.map(
(f) {
return
Container(
key: UniqueKey(),
decoration:
const
BoxDecoration(
border: Border(
bottom: BorderSide(
width:
5.0
,
color: Colors.grey,
),
),
),
child: Column(
key: UniqueKey(),
children: <Widget>[
Card(
key: UniqueKey(),
elevation:
0.0
,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
5.0
))),
child: Image.memory(
_bytes(f.productImgBase64),
fit: BoxFit.cover,
height:
250.0
,
width: MediaQuery.of(context)
.size
.width,
),
clipBehavior: Clip.antiAlias,
margin: EdgeInsets.all(
0.0
),
),
Text(
f.productBillName,
style: TextStyle(fontSize:
16
),
textAlign: TextAlign.center,
),
Container(
decoration:
const
BoxDecoration(
border: Border(
top: BorderSide(
width:
1.0
,
color: Colors.grey)),
),
child: Row(
key: UniqueKey(),
mainAxisAlignment:
MainAxisAlignment.end,
children: <Widget>[
ButtonTheme.bar(
key: UniqueKey(),
child: ButtonBar(
key: UniqueKey(),
children: <Widget>[
FlatButton(
key: UniqueKey(),
shape:
new
RoundedRectangleBorder(
borderRadius:
new
BorderRadius
.circular(
Fn.btnRadius),
),
child: IconButton(
onPressed: () {
setState(() {
f.reqqty = (
int
.parse(f.reqqty) >
1
?
int
.parse(f.reqqty) -
1
:
1
)
.toString();
});
},
icon: Icon(Icons
.remove_circle_outline),
),
onPressed: () {},
),
WidgetQty(),
// Container(
// decoration: BoxDecoration(
// color: new Color(
// 0x000000)),
// child: Text(
// f.reqqty,
// style: TextStyle(
// fontSize: 30,
// ),
// ),
// ),
WidgetbtnQtyMore(),
// FlatButton(
// shape: new RoundedRectangleBorder(
// borderRadius:
// new BorderRadius
// .circular(
// Fn.btnRadius)),
// child: IconButton(
// onPressed: () {
// setState(() {
// f.reqqty = (int.parse(
// f.reqqty) +
// 1)
// .toString();
// });
// },
// icon: Icon(Icons
// .add_circle_outline),
// ),
// onPressed: () {},
// ),
WidgetbtnAddToCart(),
],
),
)
],
),
),
],
),
);
},
).toList(),
),
),
],
),
)
: !loadhometabeFail
? Container(
color: Colors.blue[
700
],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
valueColor:
new
AlwaysStoppedAnimation<Color>(
Colors.green),
),
Padding(
padding:
const
EdgeInsets.only(top:
20.0
),
),
Text(
'Loading......'
,
style: TextStyle(
color: Colors.white,
),
),
],
),
)
: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.warning),
Padding(
padding:
const
EdgeInsets.fromLTRB(
0.0
,
20.0
,
0
,
0
),
child:
Text(
':) Problem with connection....!'
),
),
Padding(
padding:
const
EdgeInsets.fromLTRB(
10
,
20
,
0
,
0
),
child: ListTile(
title: Text(
'Try again'
,
style: TextStyle(
decoration: TextDecoration.underline,
),
textAlign: TextAlign.center,
),
onTap: () {
setState(() {
loadhometabeFail =
false
;
});
_refreshData();
},
),
),
],
),
),
Column(
children: <Widget>[
Icon(IconData(
57573
, fontFamily:
'MaterialIcons'
)),
],
),
Column(
children: <Widget>[
Icon(IconData(
59638
, fontFamily:
'MaterialIcons'
)),
],
),
],
),
//************************* Bottom Toolbar *************************
bottomNavigationBar: Container(
decoration:
const
BoxDecoration(
//color: Colors.deepOrange,
border: Border(
left: BorderSide(width:
0.0
, color: Color(
0xFFFFFFFFFF
)),
right: BorderSide(width:
0.0
, color: Color(
0xFFFF000000
)),
top: BorderSide(
width:
2.0
,
color: Colors.grey,
),
bottom: BorderSide(width:
0.0
, color: Color(
0xFFFFFFFFFF
)),
),
),
child: TabBar(
controller: _tabController,
tabs: myTabs,
labelColor: Colors.grey[
700
],
//unselectedLabelColor: colorToolbar,
indicatorSize: TabBarIndicatorSize.label,
indicatorPadding: EdgeInsets.all(
5.0
),
indicatorColor: Colors.red,
indicatorWeight:
0.1
,
onTap: (index) {
// print(index);
// Toast.show(
// 'msg : ' + index.toString(),
// context,
// duration: Toast.TOP,
// gravity: Toast.LENGTH_LONG,
// );
},
//controller: Text('data'),
),
),
),
),
),
),
);
}
}
class
WidgetQty
extends
StatelessWidget {
@override
Widget build(BuildContext context) {
final
MyInheritedWidgetDataState state = MyInheritedWidgetData.of(context);
print(
"build Widget WidgetQty"
+ state.i.toString());
return
Container(
key: UniqueKey(),
decoration: BoxDecoration(color:
new
Color(
0x000000
)),
child: Text(
state.qty.toString(),
style: TextStyle(
fontSize:
30
,
),
),
);
}
}
class
WidgetbtnQtyMore
extends
StatelessWidget {
@override
Widget build(BuildContext context) {
print(
"build Widget WidgetQtyMore"
);
final
MyInheritedWidgetDataState state =
MyInheritedWidgetData.of(context,
false
);
return
FlatButton(
key: UniqueKey(),
shape:
new
RoundedRectangleBorder(
borderRadius:
new
BorderRadius.circular(Fn.btnRadius)),
child: IconButton(
key: UniqueKey(),
onPressed: () {
state.setQty(
1
);
return
;
},
icon: Icon(Icons.add_circle_outline),
),
onPressed: () {},
);
}
}
class
WidgetCartBadge
extends
StatelessWidget {
@override
Widget build(BuildContext context) {
final
MyInheritedWidgetDataState widget = MyInheritedWidgetData.of(context);
return
Stack(
children: <Widget>[
IconButton(
onPressed: () {},
icon: Icon(Icons.shopping_cart),
),
widget.badgeNumer >
0
? Positioned(
right:
1
,
top:
11
,
child:
new
Container(
padding: EdgeInsets.all(
2
),
decoration:
new
BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(
6
),
),
constraints: BoxConstraints(
minWidth:
14
,
minHeight:
14
,
),
child: Text(
widget.badgeNumer.toString(),
style: TextStyle(
color: Colors.white,
fontSize:
8
,
),
textAlign: TextAlign.center,
),
),
)
: Container(),
],
);
}
}
class
WidgetbtnAddToCart
extends
StatelessWidget {
@override
Widget build(BuildContext context) {
final
_HomePageState _homePageState = _HomePageState();
final
MyInheritedWidgetDataState state =
MyInheritedWidgetData.of(context,
false
);
return
FlatButton(
shape:
new
RoundedRectangleBorder(
borderRadius:
new
BorderRadius.circular(Fn.btnRadius)),
child: IconButton(
onPressed: () {
state.setbadgeNumer(
2
);
_homePageState.badgeNumer = state.badgeNumer;
print(_homePageState.badgeNumer);
},
icon: Icon(Icons.shopping_cart),
),
onPressed: () {},
);
}
}
Reply
Answers (
2
)
ListView item as a progress bar
Monthly alarm in Android