dart - Flutter: Pass data from Stateful class to another class
问题描述
I need to pass data (basketCount
) from Stateful
class (DashboardState
) to another class doesn't support state (TestTabBarDelegate
). Both class are in the same file. How can I make it?
I tried mixins
but mixins
don't work with a Stateful
class.
import 'dart:convert';
import 'package:benyaghlane/widgets/default_aap_bar_row.dart';
import 'package:flutter/material.dart';
import 'package:benyaghlane/pages/liste_panier.dart';
import 'package:benyaghlane/pages/produit_sauvegarde.dart';
import 'package:benyaghlane/widgets/grid_categories.dart';
import 'package:benyaghlane/widgets/grid_meilleurs_ventes.dart';
import 'package:benyaghlane/widgets/grid_produits_fards.dart';
import 'package:benyaghlane/widgets/side_drawer.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:carousel_slider/carousel_slider.dart';
class TestTabBarDelegate extends SliverPersistentHeaderDelegate {
TestTabBarDelegate({this.controller});
final TabController controller;
@override
double get minExtent => 85.0;
@override
double get maxExtent => 85.0;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return new Container(
height: 200.0,
child: new TabBar(
controller: controller,
key: new PageStorageKey<Type>(TabBar),
labelColor: Colors.black,
labelStyle: TextStyle(color: Colors.black, fontSize: 12.0),
indicatorColor: Color(0xff93b800),
tabs: [
Tab(
icon: Icon(
Icons.home,
color: Color(0xff93b800),
),
text: "ACCUEIL",
),
Tab(
icon: Icon(Icons.favorite_border, color: Colors.red),
text: "SAUVEGARDER",
),
Tab(
text: "PANIER",
icon: Stack(
overflow: Overflow.visible,
children: <Widget>[
Icon(Icons.shopping_cart, color: Color(0xffda9a25)),
Positioned(
left: 16.0,
bottom: 12.0,
child: Container(
padding: EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: Color(0xff93b800), shape: BoxShape.circle),
child: Center(
child: Text(
"$basketCount",
style: TextStyle(color: Colors.white),
),
),
),
)
],
)),
],
),
);
}
@override
bool shouldRebuild(covariant TestTabBarDelegate oldDelegate) {
return oldDelegate.controller != controller;
}
}
class Dashboard extends StatefulWidget {
@override
DashboardState createState() => new DashboardState();
int index;
Dashboard(int index) {
this.index = index;
}
}
class DashboardState extends State<Dashboard> with TickerProviderStateMixin {
ScrollController _scrollController = new ScrollController();
TabController _tabController;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
int basketCount = 0;
Future _getBasket() async {
final SharedPreferences prefs = await _prefs;
var b = prefs.getString('basket') ?? '';
if (b != '' && b != '[]') {
var basket = json.decode(b);
// this.basketCount = basket.length;
print(basket.length);
return basket.length;
}
}
@override
void initState() {
super.initState();
_scrollController = new ScrollController();
_tabController =
new TabController(length: 3, vsync: this, initialIndex: widget.index);
}
@override
void dispose() {
_scrollController.dispose();
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new PreferredSize(
preferredSize: new Size(MediaQuery.of(context).size.width, 60.0),
child: new DefaultAppBar()),
body: Container(
margin: EdgeInsets.only(top: 30.0),
child: new NestedScrollView(
controller: _scrollController,
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
new SliverPersistentHeader(
pinned: false,
delegate: new TestTabBarDelegate(controller: _tabController),
),
];
},
body: new TestHomePageBody(
tabController: _tabController,
scrollController: _scrollController,
),
),
),
drawer: SideDrawer(),
);
}
}
final List<String> imgList = [
'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
'https://images.unsplash.com/photo-1523205771623-e0faa4d2813d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=89719a0d55dd05e2deae4120227e6efc&auto=format&fit=crop&w=1953&q=80',
'https://images.unsplash.com/photo-1508704019882-f9cf40e475b4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c6e5e3aba713b17aa1fe71ab4f0ae5b&auto=format&fit=crop&w=1352&q=80',
'https://images.unsplash.com/photo-1519985176271-adb1088fa94c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80'
];
final List child = map<Widget>(
imgList,
(index, i) {
return Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Stack(children: <Widget>[
Image.network(i, fit: BoxFit.fill, width: 1000.0),
Positioned(
bottom: 0.0,
left: 0.0,
right: 0.0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(200, 0, 0, 0),
Color.fromARGB(0, 0, 0, 0)
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
),
),
padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
child: Text(
'No. $index image',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
),
]),
),
);
},
).toList();
List<T> map<T>(List list, Function handler) {
List<T> result = [];
for (var i = 0; i < list.length; i++) {
result.add(handler(i, list[i]));
}
return result;
}
class TestHomePageBody extends StatefulWidget {
TestHomePageBody({this.scrollController, this.tabController});
final ScrollController scrollController;
final TabController tabController;
TestHomePageBodyState createState() => new TestHomePageBodyState();
}
class TestHomePageBodyState extends State<TestHomePageBody> {
Key _key = new PageStorageKey({});
bool _innerListIsScrolled = false;
void _updateScrollPosition() {
if (!_innerListIsScrolled &&
widget.scrollController.position.extentAfter == 0.0) {
setState(() {
_innerListIsScrolled = true;
});
} else if (_innerListIsScrolled &&
widget.scrollController.position.extentAfter > 0.0) {
setState(() {
_innerListIsScrolled = false;
// Reset scroll positions of the TabBarView pages
_key = new PageStorageKey({});
});
}
}
@override
void initState() {
widget.scrollController.addListener(_updateScrollPosition);
super.initState();
}
@override
void dispose() {
widget.scrollController.removeListener(_updateScrollPosition);
super.dispose();
}
@override
Widget build(BuildContext context) {
return new TabBarView(
controller: widget.tabController,
key: _key,
children: <Widget>[
SingleChildScrollView(
child: Column(
children: <Widget>[
CarouselSlider(
viewportFraction: 1.0,
aspectRatio: 2.0,
autoPlay: true,
enlargeCenterPage: false,
items: map<Widget>(
imgList,
(index, i) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(i), fit: BoxFit.cover),
),
);
},
),
),
Container(
margin: EdgeInsets.only(top: 20.0, bottom: 20.0),
child: new Column(
children: <Widget>[
GridCategories(),
SizedBox(
height: 20.0,
),
CarouselSlider(
viewportFraction: 1.0,
aspectRatio: 2.0,
autoPlay: true,
enlargeCenterPage: false,
items: map<Widget>(
imgList,
(index, i) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(i), fit: BoxFit.cover),
),
);
},
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: Text('Meilleurs ventes',
style: TextStyle(fontSize: 25.0)),
),
GridMeilleurVente(),
SizedBox(
height: 20.0,
),
CarouselSlider(
viewportFraction: 1.0,
aspectRatio: 2.0,
autoPlay: true,
enlargeCenterPage: false,
items: map<Widget>(
imgList,
(index, i) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(i), fit: BoxFit.cover),
),
);
},
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: Text('Produits Phare',
style: TextStyle(fontSize: 25.0)),
),
GridProduitsFards(),
],
),
),
],
),
),
ProduitSauvegarder(),
ListPanier(),
],
);
}
}
I expect to show this data inside the widget of the second class TestTabBarDelegate
.
解决方案
在您的声明中,您TestTabBarDelegate
可以添加一个参数,例如:
TestTabBarDelegate({this.controller, this.basketCount)};
final int basketCount
然后basketCount
在您需要显示它时参考,例如在您的文本中您可以使用"$basketCount"
.
要在那里获取数据,当您创建它时,您可以使用:
return <Widget>[
new SliverPersistentHeader(
pinned: false,
delegate: new TestTabBarDelegate(controller: _tabController, basketCount: basketCount),
),
];
推荐阅读
- java-8 - 从 HashMap 过滤值
> 使用 Java8 概念 - javascript - 如果返回的图片是 1x1,则使用备用图片的创造性方法
- regression - 回归哑元*李克特量表
- kotlin - 如何在将房间数据库中的 LiveData 分配给变量之前对其进行调整
- elasticsearch - 我们可以在 AfterSaveCallback 事件回调中更新索引文档吗
- sql-server - SQL Server 分母被推到零
- node.js - Mongoose Schemme 未验证
- powershell - 当在PowerShell中调整窗口大小时,具有背景颜色的Write-Host会用背景颜色填充整行
- shell - 如何在Shell中获取另一个字符串中的字符串的行号
- python - 如何从 sys.stdin 读取单词并过滤以“iary”结尾的单词