showBottomSheet Scaffold issue with context - dart

Trying to implement showBottomSheet into my app, but it is throwing an error: Scaffold.of() called with a context that does not contain a Scaffold.
After searching the web a bit, I added a GlobalKey but that seems like it is not doing the trick. Does anyone have a suggestion?
class _DashboardState extends State<Dashboard> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
int _bottomNavBarCurrentIndex = 0;
dashboardViews.DashboardView dView = new dashboardViews.DashboardView();
List<Widget> _listOffers = new List<Widget>();
Widget _currentView;
void loadDashboardView() {
_currentView = (_bottomNavBarCurrentIndex == 0
? dView.getOfferView(_listOffers, _getOfferData)
: dView.getOrdersView());
}
_showInfoSheet() {
showBottomSheet(
context: _scaffoldKey.currentContext,
builder: (context) {
return Text('Hello');
});
}
Future _getOfferData() async {
loadDashboardView();
List<Widget> _resultsOffers = new List<Widget>();
SharedPreferences prefs = await SharedPreferences.getInstance();
String _token = prefs.getString('token');
final responseOffers =
await http.get(globals.apiConnString + 'GetActiveOffers?token=$_token');
if (responseOffers.statusCode == 200) {
List data = json.decode(responseOffers.body);
for (var i = 0; i < data.length; i++) {
_resultsOffers.add(GestureDetector(
onTap: () => _showInfoSheet(),
child: Card(
child: Padding(
padding: EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(children: <Widget>[
Expanded(
flex: 5,
child: Text('${data[i]['Title']}',
style: TextStyle(
fontWeight: FontWeight.bold,
color: globals.themeColor4))),
Expanded(
flex: 3,
child: Row(children: <Widget>[
Icon(Icons.access_time,
size: 15, color: Colors.grey),
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 10, 0),
child: Text('11:30 PM',
style:
TextStyle(color: Colors.black))),
])),
Expanded(
flex: 1,
child: Row(children: <Widget>[
Icon(Icons.local_dining,
size: 15, color: Colors.grey),
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text('${i.toString()}',
style:
TextStyle(color: Colors.black))),
])),
]),
Padding(padding: EdgeInsets.all(10)),
Row(children: <Widget>[
Text(
'Created May 2, 2019 at 2:31 PM',
style: TextStyle(color: Colors.grey[600]),
textAlign: TextAlign.start,
)
])
])))));
}
}
setState(() {
_listOffers = _resultsOffers;
});
loadDashboardView();
}
}
void _bottomNavBarTap(int index) {
setState(() {
_bottomNavBarCurrentIndex = index;
loadDashboardView();
});
}
void pullRefresh() {
_getOfferData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.grey[200],
body: _currentView,
bottomNavigationBar: BottomNavigationBar(
onTap: _bottomNavBarTap,
currentIndex: _bottomNavBarCurrentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.near_me), title: Text('OFFERS')),
BottomNavigationBarItem(
icon: Icon(Icons.broken_image), title: Text('ORDERS'))
],
),
);
}
}
Hope someone can point me in the right direction, thanks!
EDIT: Here is one of the links I looked at with the same problem, and I tried setting the builder context to c as suggested but didn't work: https://github.com/flutter/flutter/issues/23234
EDIT 2: Adding screenshot that shows the variable contents when I'm getting the Scaffold.of() called with a context that does not contain a Scaffold error.

The reason you're getting this error is because you're calling Scaffold during its build process, and thus your showBottomSheet function can't see it. A workaround this problem is to provide a stateful widget with a Scaffold, assign the Scaffold a key , and then pass it to your Dashboard (I assumed it is the name of your stateful widget from your state class). You don't need to assign a key to the Scaffold inside the build of _DashboardState.
This is the class where you provide a Scaffold with key:
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState() ;
}
class _DashboardPageState extends State<DashboardPage> {
final GlobalKey<ScaffoldState> scaffoldStateKey ;
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldStateKey,
body: Dashboard(scaffoldKey: scaffoldStateKey),
);
}
Your original Dashboard altered :
class Dashboard extends StatefulWidget{
Dashboard({Key key, this.scaffoldKey}):
super(key: key);
final GlobalKey<ScaffoldState> scaffoldKey ;
#override
_DashboardState createState() => new _DashboardState();
}
Your _DashboardState with changes outlined :
class _DashboardState extends State<Dashboard> {
int _bottomNavBarCurrentIndex = 0;
dashboardViews.DashboardView dView = new dashboardViews.DashboardView();
List<Widget> _listOffers = new List<Widget>();
Widget _currentView;
void loadDashboardView() {
_currentView = (_bottomNavBarCurrentIndex == 0
? dView.getOfferView(_listOffers, _getOfferData)
: dView.getOrdersView());
}
_showInfoSheet() {
showBottomSheet(
context: widget.scaffoldKey.currentContext, // referencing the key passed from [DashboardPage] to use its Scaffold.
builder: (context) {
return Text('Hello');
});
}
Future _getOfferData() async {
loadDashboardView();
List<Widget> _resultsOffers = new List<Widget>();
SharedPreferences prefs = await SharedPreferences.getInstance();
String _token = prefs.getString('token');
final responseOffers =
await http.get(globals.apiConnString + 'GetActiveOffers?token=$_token');
if (responseOffers.statusCode == 200) {
List data = json.decode(responseOffers.body);
for (var i = 0; i < data.length; i++) {
_resultsOffers.add(GestureDetector(
onTap: () => _showInfoSheet(),
child: Card(
child: Padding(
padding: EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(children: <Widget>[
Expanded(
flex: 5,
child: Text('${data[i]['Title']}',
style: TextStyle(
fontWeight: FontWeight.bold,
color: globals.themeColor4))),
Expanded(
flex: 3,
child: Row(children: <Widget>[
Icon(Icons.access_time,
size: 15, color: Colors.grey),
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 10, 0),
child: Text('11:30 PM',
style:
TextStyle(color: Colors.black))),
])),
Expanded(
flex: 1,
child: Row(children: <Widget>[
Icon(Icons.local_dining,
size: 15, color: Colors.grey),
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
child: Text('${i.toString()}',
style:
TextStyle(color: Colors.black))),
])),
]),
Padding(padding: EdgeInsets.all(10)),
Row(children: <Widget>[
Text(
'Created May 2, 2019 at 2:31 PM',
style: TextStyle(color: Colors.grey[600]),
textAlign: TextAlign.start,
)
])
])))));
}
}
setState(() {
_listOffers = _resultsOffers;
});
loadDashboardView();
}
void _bottomNavBarTap(int index) {
setState(() {
_bottomNavBarCurrentIndex = index;
loadDashboardView();
});
}
void pullRefresh() {
_getOfferData();
}
#override
Widget build(BuildContext context) {
// Scaffold key has been removed as there is no further need to it.
return Scaffold(
backgroundColor: Colors.grey[200],
body: _currentView,
bottomNavigationBar: BottomNavigationBar(
onTap: _bottomNavBarTap,
currentIndex: _bottomNavBarCurrentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.near_me), title: Text('OFFERS')),
BottomNavigationBarItem(
icon: Icon(Icons.broken_image), title: Text('ORDERS'))
],
),
);
}
}
}

Related

VideoEditorController breaks all VideoPlayers in parent widgets

I have a page where I crop and trim the video.
When I initialize a VideoEditorController and for example edit the video, or just navigate back to previous page. And then I get method channel error and all CachedVideoPlayer widgets show a black screen. if we rebuild the widget with CachedVideoPlayer it'll play. And if we try to repeat the same process again for some strange reason CachedVideoPlayers won't crash.
I'm testing on a real device(Iphone 12 mini).
Error:
MissingPluginException(No implementation found for method cancel on channel flutter.io/videoPlayer/videoEvents171)
How I initialize VideoEditorController
#override
void initState() {
super.initState();
_controller = VideoEditorController.file(widget.file,
maxDuration: const Duration(seconds: 30))
..initialize().then((_) => setState(() {
_controller.preferredCropAspectRatio = widget.aspectRatio;
showTrimmer = true;
}));
}
CropScreen
class CropScreen extends StatefulWidget {
const CropScreen({
Key? key,
required this.file,
required this.exportedFile,
required this.aspectRatio,
}) : super(key: key);
final File file;
final double aspectRatio;
final Function(File) exportedFile;
#override
State<CropScreen> createState() => _CropScreenState();
}
class _CropScreenState extends State<CropScreen> {
late VideoEditorController _controller;
final double height = 60;
bool showTrimmer = false;
final ValueNotifier<bool> _isLoadingNotifier = ValueNotifier(false);
void show() {
_isLoadingNotifier.value = true;
}
void hide() {
_isLoadingNotifier.value = false;
}
#override
void initState() {
super.initState();
_controller = VideoEditorController.file(widget.file,
maxDuration: const Duration(seconds: 30))
..initialize().then((_) => setState(() {
_controller.preferredCropAspectRatio = widget.aspectRatio;
showTrimmer = true;
}));
}
#override
void dispose() {
// TODO: implement dispose
super.dispose();
_controller.dispose();
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: _isLoadingNotifier,
builder: (context, value, child) {
return Stack(
children: [
Stack(
children: [
Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(30),
child: Column(children: [
Row(children: [
Expanded(
child: IconButton(
onPressed: () => _controller
.rotate90Degrees(RotateDirection.left),
icon: const Icon(
Icons.rotate_left,
color: white,
),
),
),
Expanded(
child: IconButton(
onPressed: () => _controller
.rotate90Degrees(RotateDirection.right),
icon: const Icon(
Icons.rotate_right,
color: white,
),
),
)
]),
const SizedBox(height: 15),
Expanded(
child: CropGridViewer(
controller: _controller, horizontalMargin: 60),
),
const SizedBox(
height: 15,
),
showTrimmer
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: _trimSlider(context))
: SizedBox(height: 100),
const SizedBox(height: 15),
Row(children: [
Expanded(
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Center(
child: Text(
"Cancel",
style: MainTheme.of(context)
.bodyText1
.copyWith(fontWeight: FontWeight.w600),
),
),
),
),
buildSplashTap("21:9", 21 / 9,
padding:
const EdgeInsets.symmetric(horizontal: 10)),
buildSplashTap("1:1", 1 / 1),
buildSplashTap("4:5", 4 / 5,
padding:
const EdgeInsets.symmetric(horizontal: 10)),
buildSplashTap("NO", null,
padding: const EdgeInsets.only(right: 10)),
Expanded(
child: IconButton(
onPressed: () async {
//2 WAYS TO UPDATE CROP
//WAY 1:
show();
_controller.updateCrop();
await _controller.exportVideo(
onCompleted: (file) {
print(file!.path);
widget.exportedFile(file);
hide();
Navigator.pop(context);
});
/*WAY 2:
controller.minCrop = controller.cacheMinCrop;
controller.maxCrop = controller.cacheMaxCrop;
*/
},
icon: Center(
child: Text(
"Crop",
style: MainTheme.of(context)
.bodyText1
.copyWith(fontWeight: FontWeight.w600),
),
),
),
),
]),
]),
),
),
),
],
),
if (value)
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 4.0, sigmaY: 4.0),
child: const Opacity(
opacity: 0.8,
child:
ModalBarrier(dismissible: false, color: Colors.black),
),
),
if (value)
Center(
child: FutureBuilder(
future: Future.delayed(Duration(milliseconds: 500)),
builder: (context, snapshot) {
return const SpinKitFadingCircle(
size: 60, color: primary);
},
),
),
],
);
});
}
Widget buildSplashTap(
String title,
double? aspectRatio, {
EdgeInsetsGeometry? padding,
}) {
return InkWell(
onTap: () => _controller.preferredCropAspectRatio = aspectRatio,
child: Padding(
padding: padding ?? EdgeInsets.zero,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.aspect_ratio, color: Colors.white),
Text(
title,
style: const TextStyle(fontWeight: FontWeight.bold, color: white),
),
],
),
),
);
}
List<Widget> _trimSlider(BuildContext context) {
return [
AnimatedBuilder(
animation: _controller.video,
builder: (_, __) {
final duration = _controller.video.value.duration.inSeconds;
final pos = _controller.trimPosition * duration;
final start = _controller.minTrim * duration;
final end = _controller.maxTrim * duration;
return Padding(
padding: EdgeInsets.symmetric(horizontal: height / 4),
child: Row(children: [
Text(
formatter(Duration(seconds: pos.toInt())),
style: MainTheme.of(context).bodyText1,
),
const Expanded(child: SizedBox()),
OpacityTransition(
visible: _controller.isTrimming,
child: Row(mainAxisSize: MainAxisSize.min, children: [
Text(
formatter(Duration(seconds: start.toInt())),
style: MainTheme.of(context).bodyText1,
),
const SizedBox(width: 10),
Text(
formatter(Duration(seconds: end.toInt())),
style: MainTheme.of(context).bodyText1,
),
]),
)
]),
);
},
),
Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(vertical: height / 4),
child: TrimSlider(
controller: _controller,
height: height,
horizontalMargin: height / 4,
child: TrimTimeline(
controller: _controller,
margin: const EdgeInsets.only(top: 10))),
)
];
}
String formatter(Duration duration) => [
duration.inMinutes.remainder(60).toString().padLeft(2, '0'),
duration.inSeconds.remainder(60).toString().padLeft(2, '0')
].join(":");
}
To use VideoEditorController you need to add this package:
video_editor: ^1.4.1
Dart SDK:
sdk: ">=2.16.1 <3.0.0"

Flutter: `onPressed` acts on all `IconButton`s in a list view

I want to change color of every icon after pressing. But all of icons in a ExpandableContainerchange after pressing one of them.
class _ExpandableListViewState extends State<ExpandableListView> {
bool expandFlag = false;
Color _iconColor = Colors.white;
#override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.symmetric(vertical: 1.0),
child: new Column(
children: <Widget>[
new Container(
.
.
.
),
new ExpandableContainer(
expanded: expandFlag,
expandedHeight: ...
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
decoration:
new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.grey), color: Colors.black),
child: new ListTile(
title: ...
leading: new IconButton(
icon: Icon(Icons.star, color: _iconColor),
onPressed: () {
setState(() {
_iconColor = _iconColor == Colors.white ? Colors.yellow : Colors.white;
});
},
),
subtitle: ...
),
);
},
itemCount: ...,
))
],
),
);
}
}
class ExpandableContainer extends StatelessWidget {
final bool expanded;
final double expandedHeight;
final Widget child;
ExpandableContainer({
#required this.child,
this.expandedHeight,
this.expanded = true,
});
#override
Widget build(BuildContext context) {
.
.
.
}
Whole code:
import 'package:flutter/material.dart';
import 'data.dart';
void main() {
runApp(new MaterialApp(home: new Home()));
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.grey,
appBar: new AppBar(
title: new Text("Expandable List", style: TextStyle(color: Colors.black)),
backgroundColor: Colors.lightGreen,
),
body: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new ExpandableListView(title: broadcast[index].title, ind: index);
},
itemCount: broadcast.length,
),
);
}
}
class ExpandableListView extends StatefulWidget {
final String title;
final int ind;
const ExpandableListView({this.title, this.ind});
#override
_ExpandableListViewState createState() => new _ExpandableListViewState();
}
class _ExpandableListViewState extends State<ExpandableListView> {
bool expandFlag = false;
Color _iconColor = Colors.white;
#override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.symmetric(vertical: 1.0),
child: new Column(
children: <Widget>[
new Container(
color: Colors.blue[300],
padding: new EdgeInsets.symmetric(horizontal: 5.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new IconButton(
icon: new Container(
height: 50.0,
width: 50.0,
decoration: new BoxDecoration(
color: Colors.deepOrange,
shape: BoxShape.circle,
),
child: new Center(
child: new Icon(
expandFlag ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
color: Colors.white,
size: 30.0,
),
),
),
onPressed: () {
setState(() {
expandFlag = !expandFlag;
});
}),
new Text(
widget.title,
style: new TextStyle(fontWeight: FontWeight.bold,fontSize: 20.0, color: Colors.black87),
)
],
),
),
new ExpandableContainer(
expanded: expandFlag,
expandedHeight: 90.0 * (broadcast[widget.ind].contents.length < 4 ? broadcast[widget.ind].contents.length : 4), // + (0.0 ?: 29.0),
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
decoration:
new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.grey), color: Colors.black),
child: new ListTile(
title: new Text(
broadcast[widget.ind].contents[index],
style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.lightGreen),
textAlign: TextAlign.right,
),
leading: new IconButton(
icon: Icon(Icons.star, color: _iconColor),
onPressed: () {
setState(() {
_iconColor = _iconColor == Colors.white ? Colors.yellow : Colors.white;
});
},
),
subtitle: new Text ('${broadcast[widget.ind].team[index]}\n${broadcast[widget.ind].time[index]} ${broadcast[widget.ind].channel[index]}',
textAlign: TextAlign.right, style:TextStyle(color: Colors.white)),
isThreeLine: true,
),
);
},
itemCount: broadcast[widget.ind].contents.length,
))
],
),
);
}
}
class ExpandableContainer extends StatelessWidget {
final bool expanded;
final double expandedHeight;
final Widget child;
//final Color iconColor;
ExpandableContainer({
#required this.child,
this.expandedHeight,
this.expanded = true,
//this.iconColor,
});
#override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return new AnimatedContainer(
duration: new Duration(milliseconds: 100),
curve: Curves.easeInOut,
width: screenWidth,
height: expanded ? expandedHeight : 0.0,
child: new Container(
child: child,
decoration: new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.blue)),
),
);
}
}
You need to make the list item a StatefulWidget in which you have the state _iconColor
Stateful List Tile
class StatefulListTile extends StatefulWidget {
const StatefulListTile({this.subtitle, this.title});
final String subtitle, title;
#override
_StatefulListTileState createState() => _StatefulListTileState();
}
class _StatefulListTileState extends State<StatefulListTile> {
Color _iconColor = Colors.white;
#override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(
border: new Border.all(width: 1.0, color: Colors.grey),
color: Colors.black),
child: new ListTile(
title: new Text(
widget?.title ?? "",
style: new TextStyle(
fontWeight: FontWeight.bold, color: Colors.lightGreen),
textAlign: TextAlign.right,
),
leading: new IconButton(
icon: Icon(Icons.star, color: _iconColor),
onPressed: () {
setState(() {
_iconColor =
_iconColor == Colors.white ? Colors.yellow : Colors.white;
});
},
),
subtitle: new Text(widget?.subtitle ?? "",
textAlign: TextAlign.right, style: TextStyle(color: Colors.white)),
isThreeLine: true,
),
);
}
}
Usage
class ExpandableListView extends StatefulWidget {
final String title;
final int ind;
const ExpandableListView({this.title, this.ind});
#override
_ExpandableListViewState createState() => new _ExpandableListViewState();
}
class _ExpandableListViewState extends State<ExpandableListView> {
bool expandFlag = false;
Color _iconColor = Colors.white;
#override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.symmetric(vertical: 1.0),
child: new Column(
children: <Widget>[
new Container(
color: Colors.blue[300],
padding: new EdgeInsets.symmetric(horizontal: 5.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new IconButton(
icon: new Container(
height: 50.0,
width: 50.0,
decoration: new BoxDecoration(
color: Colors.deepOrange,
shape: BoxShape.circle,
),
child: new Center(
child: new Icon(
expandFlag
? Icons.keyboard_arrow_up
: Icons.keyboard_arrow_down,
color: Colors.white,
size: 30.0,
),
),
),
onPressed: () {
setState(() {
expandFlag = !expandFlag;
});
}),
new Text(
widget.title,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.black87),
)
],
),
),
new ExpandableContainer(
expanded: expandFlag,
expandedHeight: 90.0 *
(broadcast[widget.ind].contents.length < 4
? broadcast[widget.ind].contents.length
: 4), // + (0.0 ?: 29.0),
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return StatefulListTile(
title: broadcast[widget.ind].contents[index],
subtitle:
'${broadcast[widget.ind].team[index]}\n${broadcast[widget.ind].time[index]} ${broadcast[widget.ind].channel[index]}',
);
},
itemCount: broadcast[widget.ind].contents.length,
))
],
),
);
}
}
You should make the color property distinct for each element in the ListView, what you are doing is that the color is global and shared among all the icons in the ListView, for this reason all icons are changing their color when one icon is pressed.
class Broadcast {
final String title;
List<String> contents;
List<String> team = [];
List<String> time = [];
List<String> channel = [];
Color iconColor = Colors.white; //initialize at the beginning
Broadcast(this.title, this.contents, this.team, this.time, this.channel); //, this.icon);
}
edit your ExpandableListView
class ExpandableListView extends StatefulWidget {
final int ind;
final Broadcast broadcast;
const ExpandableListView({this.broadcast,this.ind});
#override
_ExpandableListViewState createState() => new _ExpandableListViewState();
}
edit your Home class
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.grey,
appBar: new AppBar(
title: new Text("Expandable List", style: TextStyle(color: Colors.black)),
backgroundColor: Colors.lightGreen,
),
body: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new ExpandableListView(title: broadcast[index], ind: index);
},
itemCount: broadcast.length,
),
);
}
}
edit your _ExpandableListViewState
class _ExpandableListViewState extends State<ExpandableListView> {
bool expandFlag = false;
#override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.symmetric(vertical: 1.0),
child: new Column(
children: <Widget>[
new Container(
color: Colors.blue[300],
padding: new EdgeInsets.symmetric(horizontal: 5.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new IconButton(
icon: new Container(
height: 50.0,
width: 50.0,
decoration: new BoxDecoration(
color: Colors.deepOrange,
shape: BoxShape.circle,
),
child: new Center(
child: new Icon(
expandFlag ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
color: Colors.white,
size: 30.0,
),
),
),
onPressed: () {
setState(() {
expandFlag = !expandFlag;
});
}),
new Text(
widget.broadcast.title,
style: new TextStyle(fontWeight: FontWeight.bold,fontSize: 20.0, color: Colors.black87),
)
],
),
),
new ExpandableContainer(
expanded: expandFlag,
expandedHeight: 90.0 * (broadcast[widget.ind].contents.length < 4 ? broadcast[widget.ind].contents.length : 4), // + (0.0 ?: 29.0),
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Container(
decoration:
new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.grey), color: Colors.black),
child: new ListTile(
title: new Text(
broadcast[widget.ind].contents[index],
style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.lightGreen),
textAlign: TextAlign.right,
),
leading: new IconButton(
icon: Icon(Icons.star, color: widget.broadcast.iconColor),
onPressed: () {
setState(() {
widget.broadcast.iconColor = widget.broadcast.iconColor == Colors.white ? Colors.yellow : Colors.white;
});
},
),
subtitle: new Text ('${broadcast[widget.ind].team[index]}\n${broadcast[widget.ind].time[index]} ${broadcast[widget.ind].channel[index]}',
textAlign: TextAlign.right, style:TextStyle(color: Colors.white)),
isThreeLine: true,
),
);
},
itemCount: broadcast[widget.ind].contents.length,
))
],
),
);
}
}

Async call value is NULL for the first time, causing assertion error while building MainPage (Widget dirty)

I am working on a flutter widget which needs to load and update data in a Text with rest call. async call fetchPatientCount brings the data from REST resource and update the counter inside the setState method.
As a result of the below implementation, since the build method called twice, the counter value is NULL for the first time and causing the below exception.However for the second time the value is being populated.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MainPage(dirty, state: _MainPageState#9e9d8):
flutter: 'package:flutter/src/widgets/text.dart': Failed assertion: line 235 pos 15: 'data != null': is not
flutter: true.
Any help will be appreciated related to the issue.
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
String counter;
#override
void initState() {
super.initState();
fetchPatientCount().then((val) {
setState(() {
counter = val.count.toString();
});
});
}
#override
Widget build(BuildContext context) {
String text;
if(counter!=null) {
text = counter;
}
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
Text(text,/* Here text is NULL for the first time */
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}
Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
}
class PatientCount {
int count;
double amount;
PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}
Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";
Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";
String requestBody = '{"consultedOn":' + '16112018' + '}';
http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);
final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);
if (statusCode != 200 || responseBody == null) {
throw new Exception(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}
I solved my self, used FutureBuilder to resolve the issue.
Here is the full code below.
class PatientCount {
int count;
double amount;
PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}
Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";
Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";
String requestBody = '{"consultedOn":' + '16112018' + '}';
http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);
final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);
if (statusCode != 200 || responseBody == null) {
throw new FetchPatientCountException(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
/*Text(get,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))*/
buildCountWidget()
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}
Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
Widget buildCountWidget() {
Widget vistitCount = new Center(
child: new FutureBuilder<PatientCount>(
future: fetchPatientCount(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.count.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
// By default, show a loading spinner
return new CircularProgressIndicator();
},
),
);
return vistitCount;
}
}
If it's null, build a widget that says that it's loading. It will build the actual widgets in the second call that you mentioned.
Basically, do this:
#override
Widget build(BuildContext context) {
String text;
if(counter!=null) {
text = counter;
} else {
return Text("loading..."); // or a fancier progress thing
}
fetchPatientCount().then((val) {
setState(() {
counter = val.count.toString();
});
});
That's expected behavior. "async" means the result will be available eventually later and then the code passed to then will be executed.
Flutter doesn't wait for that. It calls build() for every frame.
Perhaps you wanted to change
if(counter!=null) {
text = counter;
}
to
if(counter!=null) {
text = counter;
} else {
text = 'waiting ...';
}
because otherwise text will be null and Text(null) causes the error you got.

My activity is lag, it it because of the code?

class _DaftarMuridState extends State<DaftarMurid> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Column(
children: <Widget>[
new Flexible(
child: new FirebaseAnimatedList(//new
query: db.reference().child("Murid"),
sort: (a, b) => a.key.compareTo(b.key),
padding: new EdgeInsets.all(8.0),
itemBuilder: (_, DataSnapshot dataSnapshot, Animation<double> animations,x){
return new DaftarMuridView(
snapshot: dataSnapshot,
animation: animations,
);//new
}
),
),
],
),
);
}
}
class DaftarMuridViewState extends State<DaftarMuridView>{
DaftarMuridViewState({this.snapshot, this.animation});
final DataSnapshot snapshot;
final Animation animation;
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
String fotoUrl = snapshot.value['Foto'];
String ig = snapshot.value['Instagram'];
hash.putIfAbsent(snapshot.value['Nama'], () => false);
bool expanded = hash[snapshot.value['Nama']];
var expansionPanel = new ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
setState(() {
hash.remove(snapshot.value['Nama']);
hash.putIfAbsent(snapshot.value['Nama'], () => !isExpanded);
expanded = !expanded;
});
},
children: [new ExpansionPanel(headerBuilder: (BuildContext context, bool isExpanded) {
return new ListTile(
leading: const Icon(Icons.school),
title: new Text(
snapshot.value['Nama'],
textAlign: TextAlign.left,
style: new TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w400,
),
));
},
body: new ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
children: <Widget>[
new CachedNetworkImage(
imageUrl: fotoUrl == null?"https://drive.google.com/uc?export=download&id=1tkqO59S9jiWpkzHQNJRKLuCGYIn5kK_v":fotoUrl,
placeholder: new CircularProgressIndicator(),
errorWidget: new CachedNetworkImage(imageUrl: "https://drive.google.com/uc?export=download&id=1tkqO59S9jiWpkzHQNJRKLuCGYIn5kK_v"),
fadeOutDuration: new Duration(seconds: 1),
fadeInDuration: new Duration(seconds: 1),
height: size.height / 2.0,
width: size.width / 2.0,
alignment: Alignment.center,
),
new ListTile(
leading: const Icon(Icons.today),
title: const Text('Tanggal Lahir'),
subtitle: new Text(snapshot.value['Tanggal Lahir']),
),
new Row(
children: <Widget>[
ig != null ?
new FlatButton(
onPressed: () => _instagram(ig),
child: new CachedNetworkImage(imageUrl: "http://diylogodesigns.com/blog/wp-content/uploads/2016/05/Instagram-logo-png-icon.png", width: size.width / 4.0, height: size.height / 4.0, ),
)
: new Container(),
],
),
],
),
isExpanded: expanded)],
);
return new SizeTransition(
sizeFactor: new CurvedAnimation(
parent: animation, curve: Curves.easeOut),
axisAlignment: 0.0,
child: expansionPanel,
);
}
}
is my code not efficient? the process is Get Data from Firebase -> Store it to list view
it's a bit lag when open the activity, maybe because getting the data. But is there a solution for make it doesn't lag?
I cut some code that isn't important.
Use Futures to perform time consuming operations, so it will not freeze the UI.
https://www.dartlang.org/tutorials/language/futures

Flutter - Generate in app interactivity

I'm kind of lost in generating interactivity on Flutter.
I'm trying to make tapping the FlatButtons the value shown above, and in the order it was tapped.
For example, tap number 1, then 2, 1, 1, 1 and last 2 should appear $ 12111, remembering quite a list.
Taping on the backspace icon removes the last number that has entered the list.
I am not aware of generating this communication between classes.
Can you help me? I'm trying to use the StatefulWidget but I'm not succeeding.
Below I left the code that generates the screen described above.
main.dart
import "package:flutter/material.dart";
void main() {
runApp(new KeyboardApp());
}
class KeyboardApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new ListView (
children: <Widget>[
new Number(),
new Keyboard(),
],
),
);
}
}
class NumberState extends StatefulWidget {
NumberList createState() => new NumberList();
}
class NumberList extends State<NumberState> {
List<String> numbers = <String>[];
String number;
#override
Widget build(BuildContext context) {
number = this.numbers.join('');
return new Text(
this.number,
style: new TextStyle(
fontFamily: 'Roboto',
color: new Color(0xFFFFFFFF),
fontSize: 45.0
)
);
}
}
class Number extends StatelessWidget {
final Color color = new Color(0xFFE57373);
#override
Widget build(BuildContext context) {
return new Container(
height: 145.0,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
padding: new EdgeInsets.only(right: 16.0, top: 35.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new Text(
'\$ ',
style: new TextStyle(
fontFamily: 'Roboto',
color: new Color(0xFFFFFFFF),
fontSize: 20.0
)
),
new NumberState(),
],
)
)
],
),
color: color,
);
}
}
class Keyboard extends StatelessWidget {
final Color color = new Color(0xFFE57373);
var list = new NumberList().numbers;
#override
Widget build(BuildContext context) {
return new Container(
padding: new EdgeInsets.only(right: 15.0, left: 15.0, top: 47.0, bottom: 20.0),
child: new Column(
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new FlatButton(
textColor: color,
child: new Text(
'1',
style: new TextStyle(
fontSize: 35.0
),
),
onPressed: () {
this.list.add('1');
},
),
new FlatButton(
textColor: color,
child: new Text(
'2',
style: new TextStyle(
fontSize: 35.0
),
),
onPressed: () {
this.list.add('2');
},
),
new FlatButton(
textColor: color,
child: new Icon(
Icons.backspace,
size: 35.0
),
onPressed: () {
this.list.removeLast();
},
),
],
),
],
),
);
}
}
Check out the Flutter interactivity tutorial. At a high level (heh), your problem is that you are trying to store state in the leaves of your widget tree. You should store your state higher up in your tree and then pass it down to the children.
The example below uses ValueNotifier but you can also pass state around using streams, callbacks, or even Firebase Database.
import "package:flutter/material.dart";
void main() {
runApp(new KeyboardApp());
}
class KeyboardApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomePage(),
);
}
}
class HomePage extends StatefulWidget {
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
ValueNotifier<List<int>> numbers = new ValueNotifier<List<int>>(<int>[]);
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new ListView (
children: <Widget>[
new NumberDisplay(numbers: numbers),
new Keyboard(numbers: numbers),
],
),
);
}
}
class NumberDisplay extends AnimatedWidget {
NumberDisplay({ this.numbers }) : super(listenable: numbers);
final ValueNotifier<List<int>> numbers;
final Color _color = new Color(0xFFE57373);
#override
Widget build(BuildContext context) {
return new Container(
height: 145.0,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
padding: new EdgeInsets.only(right: 16.0, top: 35.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new Text(
'\$ ',
style: new TextStyle(
fontFamily: 'Roboto',
color: new Color(0xFFFFFFFF),
fontSize: 20.0
)
),
new Text(
this.numbers.value.join(''),
style: new TextStyle(
fontFamily: 'Roboto',
color: new Color(0xFFFFFFFF),
fontSize: 45.0
),
),
],
),
),
],
),
color: _color,
);
}
}
class Keyboard extends StatelessWidget {
Keyboard({ this.numbers });
final ValueNotifier<List<int>> numbers;
final Color _color = new Color(0xFFE57373);
#override
Widget build(BuildContext context) {
return new Container(
padding: new EdgeInsets.only(right: 15.0, left: 15.0, top: 47.0, bottom: 20.0),
child: new Column(
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new FlatButton(
textColor: _color,
child: new Text(
'1',
style: new TextStyle(
fontSize: 35.0
),
),
onPressed: () {
numbers.value = new List.from(numbers.value)..add(1);
},
),
new FlatButton(
textColor: _color,
child: new Text(
'2',
style: new TextStyle(
fontSize: 35.0
),
),
onPressed: () {
numbers.value = new List.from(numbers.value)..add(2);
},
),
new FlatButton(
textColor: _color,
child: new Icon(
Icons.backspace,
size: 35.0
),
onPressed: () {
numbers.value = new List.from(numbers.value)..removeLast();
},
),
],
),
],
),
);
}
}

Resources