I am trying to test a custom widget GoogleSignInButton.
Here is the implementation of the widget:
import 'package:flutter/material.dart';
class GoogleSignInButton extends StatelessWidget {
GoogleSignInButton({this.onPressed});
final Function onPressed;
#override
Widget build(BuildContext context) {
Image _buildLogo() {
return Image.asset(
"assets/g-logo.png",
height: 18.0,
width: 18.0,
);
}
Opacity _buildText() {
return Opacity(
opacity: 0.54,
child: Text(
"Sign in with Google",
style: TextStyle(
fontFamily: 'Roboto-Medium',
color: Colors.black,
),
),
);
}
return MaterialButton(
height: 40.0,
onPressed: this.onPressed,
color: Colors.white,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_buildLogo(),
SizedBox(width: 24.0),
_buildText(),
],
),
);
}
}
I am trying to test the onPressed function callback by the test that follows.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../lib/ui/widgets/google_sign_in_button.dart';
void main() {
testWidgets('my first widget test', (WidgetTester tester) async {
var pressed = false;
var widget = GoogleSignInButton(
onPressed: () => () {
pressed = true;
},
);
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: Center(
child: widget,
),
),
);
},
),
);
await tester.press(find.byWidget(widget));
expect(pressed, equals(true));
});
}
Unfortunately, the test fails.
I am executing my widget test on the command line by flutter test test/widget_test.dart and here is the result of the test:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
Expected: <true>
Actual: <false>
When the exception was thrown, this was the stack:
#4 main.<anonymous closure> (file:///home/hans/Development/flutter/recipes_app/test/widget_test.dart:30:5)
<asynchronous suspension>
#5 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:72:23)
#6 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:566:19)
<asynchronous suspension>
#9 TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:550:14)
#10 AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:893:24)
#16 AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:890:15)
#17 testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:71:22)
#18 Declarer.test.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:168:27)
<asynchronous suspension>
#19 Invoker.waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:249:15)
<asynchronous suspension>
#24 Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:246:5)
#25 Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:166:33)
#30 Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:165:13)
<asynchronous suspension>
#31 Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:399:25)
<asynchronous suspension>
#45 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
#46 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#47 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
(elided 28 frames from class _FakeAsync, package dart:async, and package stack_trace)
This was caught by the test expectation on the following line:
file:///home/hans/Development/flutter/recipes_app/test/widget_test.dart line 30
The test description was:
my first widget test
════════════════════════════════════════════════════════════════════════════════════════════════════
00:01 +0 -1: my first widget test [E]
Test failed. See exception logs above.
The test description was: my first widget test
00:02 +0 -1: Some tests failed.
Any ideas why the test fails?
Your closure is wrong:
() => () {
pressed = true;
},
You need to write it either like that
() {
pressed = true;
},
Or like that
() => ( pressed = true )
And you need to trigger the tester.tap method.
That's my working code:
var pressed = false;
var widget = GoogleSignInButton(
onPressed: () {
pressed = true;
debugPrint("Pressed!");
},
);
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: Center(
child: widget,
),
),
);
},
),
);
expect(find.byWidget(widget), findsOneWidget);
await tester.tap(find.byWidget(widget));
expect(pressed, isTrue);
And I've supposed that when you run your project your Widget renders well and does not throw any errors.
HINT: make a flutter clean after any change in your test_file.dart change.
Related
I want to go to Second Page with Navigator.push method. So I am using ElevatedButton Widget for this purpose. I'm also using Statefull Widget. My source code like in below:
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'ScannerPage.dart';
void main() {
runApp(const QrCodeMainWindow());
}
class QrCodeMainWindow extends StatefulWidget {
const QrCodeMainWindow({Key? key}) : super(key: key);
#override
State<QrCodeMainWindow> createState() => _QrCodeMainWindowState();
}
class _QrCodeMainWindowState extends State<QrCodeMainWindow> {
final String _data = "";
QRViewController? controller;
Barcode? result;
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
#override
Widget build(BuildContext context) {
final ButtonStyle style = ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('QR Code Scanner App'),
backgroundColor: Colors.blueAccent,
),
body: Column(
children: [
ElevatedButton(
child: Text('Scan'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScannerPage()),
);
}),
Text(_data)
],
),
),
);
}
When I run this App succesfuly openning on simulator (Iphone 13). But when I press the button I get below error.
How Can I solve this error ?
======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0 Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2553:9)
#1 Navigator.of (package:flutter/src/widgets/navigator.dart:2560:6)
#2 Navigator.push (package:flutter/src/widgets/navigator.dart:2016:22)
#3 _QrCodeMainWindowState.build.<anonymous closure> (package:qr_code_scanner_example/main.dart:51:29)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
#10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
#12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
#16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#17 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#18 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#19 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#25 _invoke1 (dart:ui/hooks.dart:170:10)
#26 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#27 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#ba4ae
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(46.3, 135.7)
finalLocalPosition: Offset(46.3, 26.7)
button: 1
sent tap down
I am trying to make a flutter app. Recently, I have learned how to use hero with two different buttons which all have the same destination. So, I tried to use hero with infinitely creatable containers. This is what I came up with:
import 'package:flutter/material.dart';
void main() => runApp(MainPage());
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: Column(children: <Widget>[
Body(),
])));
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final String open1 = 'open';
int count = 1;
#override
Widget build(BuildContext context) {
print(count);
List cards = List.generate(count, (int i) => RCard(count));
return Expanded(
child: Container(
child: NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
},
child: PageView.builder(
reverse: true,
pageSnapping: false,
controller: PageController(viewportFraction: 0.85),
itemCount: count,
itemBuilder: (context, i) {
if (i == 0) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open1,
)),
);
count++;
},
child: Hero(
tag: open1,
child: Padding(
padding: EdgeInsets.only(
left:
MediaQuery.of(context).size.height *
0.015,
right:
MediaQuery.of(context).size.height *
0.015,
top: MediaQuery.of(context).size.width *
0.08,
bottom:
MediaQuery.of(context).size.width *
0.15),
child: Material(
borderRadius:
BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: InkWell(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.add,
size: 30.0,
color: Colors.black,
)
]),
)))));
} else {
return cards[i];
}
}))));
}
}
class RCard extends StatefulWidget {
final int count;
RCard(this.count);
#override
RCardState createState() => RCardState();
}
class RCardState extends State<RCard> {
int count;
String open2;
#override
void initState() {
super.initState();
count = widget.count;
open2 = 'open$count';
}
#override
Widget build(BuildContext context) {
return Hero(
tag: open2,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open2,
)),
);
},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.height * 0.015,
right: MediaQuery.of(context).size.height * 0.015,
top: MediaQuery.of(context).size.width * 0.08,
bottom: MediaQuery.of(context).size.width * 0.15),
child: Material(
borderRadius: BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: Padding(
padding:
EdgeInsets.all(MediaQuery.of(context).size.width * 0.15),
)),
)),
);
}
}
class Page extends StatelessWidget {
final String open;
Page({this.open});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Hero(
tag: open,
child: Material(
child: Center(child: Text('New page')),
)),
onTap: () {
Navigator.pop(context);
},
);
}
}
But, when I create a second container and press on it, It will give a black screen and get an error message in my debug console saying:
flutter: ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during a scheduler callback:
flutter: There are multiple heroes that share the same tag within a subtree.
flutter: Within each subtree for which heroes are to be animated (typically a PageRoute subtree), each Hero
flutter: must have a unique non-null tag.
flutter: In this case, multiple heroes had the following tag: opennull
flutter: Here is the subtree for one of the offending heroes:
flutter: # Hero(tag: opennull, state: _HeroState#f299c)
flutter: # └KeyedSubtree-[GlobalKey#45266]
flutter: # └GestureDetector
flutter: # └RawGestureDetector(state: RawGestureDetectorState#98814(gestures: [tap]))
flutter: # └_GestureSemantics(renderObject: RenderSemanticsGestureHandler#59110)
flutter: # └Listener(listeners: [down], behavior: deferToChild, renderObject: RenderPointerListener#5cfa6)
flutter: # └Padding(padding: EdgeInsets(13.4, 33.1, 13.4, 62.1), renderObject: RenderPadding#ab11d)
flutter: # └Material(type: canvas, elevation: 8.0, color: Color(0xffffffff), borderRadius: circular(40.0), state: _MaterialState#a511a)
flutter: # └_MaterialInterior(duration: 200ms, shape: RoundedRectangleBorder(BorderSide(Color(0xff000000), 0.0, BorderStyle.none), BorderRadius.circular(40.0)), elevation: 8.0, color: Color(0xffffffff), shadowColor: Color(0xff000000), state: _MaterialInteriorState#6412f(ticker inactive))
flutter: # └PhysicalShape(clipper: ShapeBorderClipper, elevation: 8.0, color: Color(0xffffffff), shadowColor: Color(0xff000000), renderObject: RenderPhysicalShape#1b504)
flutter: # └_ShapeBorderPaint
flutter: # └CustomPaint(renderObject: RenderCustomPaint#94831)
flutter: # └NotificationListener<LayoutChangedNotification>
flutter: # └_InkFeatures-[GlobalKey#8ef37 ink renderer](renderObject: _RenderInkFeatures#670e3)
flutter: # └AnimatedDefaultTextStyle(duration: 200ms, debugLabel: (englishLike body1 2014).merge(blackCupertino body1), inherit: false, color: Color(0xdd000000), family: .SF UI Text, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip, state: _AnimatedDefaultTextStyleState#9cb8b(ticker inactive))
flutter: # └DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(blackCupertino body1), inherit: false, color: Color(0xdd000000), family: .SF UI Text, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip)
flutter: # └Padding(padding: EdgeInsets.all(62.1), renderObject: RenderPadding#0a02b)
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Hero._allHeroesFor.visitor.<anonymous closure>
package:flutter/…/widgets/heroes.dart:210
flutter: #1 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:220
flutter: #2 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #3 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #4 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #5 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #6 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #7 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #8 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #9 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #10 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #11 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #12 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #13 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #14 List.forEach (dart:core/runtime/libgrowable_array.dart:278:8)
flutter: #15 SliverMultiBoxAdaptorElement.visitChildren
package:flutter/…/widgets/sliver.dart:1175
flutter: #16 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #17 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #18 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #19 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #20 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #21 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #22 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #23 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #24 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #25 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #26 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #27 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #28 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #29 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #30 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #31 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #32 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #33 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #34 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #35 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #36 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #37 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #38 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #39 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #40 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #41 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #42 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #43 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #44 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #45 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #46 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #47 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #48 Hero._allHeroesFor.visitor
flutter: #49 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #50 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #51 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #52 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #53 MultiChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4948
flutter: #54 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #55 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #56 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #57 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #58 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #59 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #60 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #61 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #62 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #63 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #64 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #65 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #66 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #67 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #68 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #69 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #70 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #71 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #72 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #73 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #74 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #75 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #76 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #77 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #78 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #79 ComponentElement.visitChildren
package:flutter/…/widgets/framework.dart:3755
flutter: #80 Hero._allHeroesFor.visitor
package:flutter/…/widgets/heroes.dart:225
flutter: #81 SingleChildRenderObjectElement.visitChildren
package:flutter/…/widgets/framework.dart:4848
flutter: #82 Element.visitChildElements
package:flutter/…/widgets/framework.dart:2686
flutter: #83 Hero._allHeroesFor
package:flutter/…/widgets/heroes.dart:227
flutter: #84 HeroController._startHeroTransition
package:flutter/…/widgets/heroes.dart:655
flutter: #85 HeroController._maybeStartHeroTransition.<anonymous closure>
package:flutter/…/widgets/heroes.dart:630
flutter: #86 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:990
flutter: #87 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:938
flutter: #88 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:842
flutter: #89 _invoke (dart:ui/hooks.dart:154:13)
flutter: #90 _drawFrame (dart:ui/hooks.dart:143:3)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
How anyone please help???
Instead of doing - List.generate in build. Simply Pass RCard directly in PageView.builder
working Code:
import 'package:flutter/material.dart';
void main() => runApp(MainPage());
class MainPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: Column(children: <Widget>[
Body(),
])));
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final String open1 = 'open';
int count = 1;
#override
Widget build(BuildContext context) {
print(count);
return Expanded(
child: Container(
child: NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
},
child: PageView.builder(
reverse: true,
pageSnapping: false,
controller: PageController(viewportFraction: 0.85),
itemCount: count,
itemBuilder: (context, i) {
if (i == 0) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open1,
)),
);
count++;
},
child: Hero(
tag: open1,
child: Padding(
padding: EdgeInsets.only(
left:
MediaQuery.of(context).size.height *
0.015,
right:
MediaQuery.of(context).size.height *
0.015,
top: MediaQuery.of(context).size.width *
0.08,
bottom:
MediaQuery.of(context).size.width *
0.15),
child: Material(
borderRadius:
BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: InkWell(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.add,
size: 30.0,
color: Colors.black,
)
]),
)))));
} else {
return RCard(i);
}
}))));
}
}
class RCard extends StatefulWidget {
final int count;
RCard(this.count);
#override
RCardState createState() => RCardState();
}
class RCardState extends State<RCard> {
int count;
String open2;
#override
void initState() {
super.initState();
count = widget.count;
open2 = 'open$count';
}
#override
Widget build(BuildContext context) {
return Hero(
tag: open2,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page(
open: open2,
)),
);
},
child: Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.height * 0.015,
right: MediaQuery.of(context).size.height * 0.015,
top: MediaQuery.of(context).size.width * 0.08,
bottom: MediaQuery.of(context).size.width * 0.15),
child: Material(
borderRadius: BorderRadius.circular(40.0),
color: Colors.white,
elevation: 8.0,
child: Padding(
padding:
EdgeInsets.all(MediaQuery.of(context).size.width * 0.15),
)),
)),
);
}
}
class Page extends StatelessWidget {
final String open;
Page({this.open});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Hero(
tag: open,
child: Material(
child: Center(child: Text('New page')),
)),
onTap: () {
Navigator.pop(context);
},
);
}
}
I'm new with flutter & just learned how to retrieve data from firestore & did some UI. Right now I have 2 problems;
1- This is a Setting Page which has CustomScrollView contains ScrollController for the controller.
SettingsPage
The controller working fine with this code
class _SettingsPageState extends State<SettingsPage> {
ScrollController _scrollController;
#override
void initState() {
super.initState();
_scrollController = new ScrollController();
_scrollController.addListener(() => setState(() {}));
}
#override
void dispose() {
_scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Shared.firestore.collection('client').document(Shared.firebaseUser.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Scaffold(
backgroundColor: Colors.grey[50],
body: Stack(
children: <Widget>[
CustomScrollView(
controller: _scrollController,
slivers: <Widget>[
SliverAppBar(
expandedHeight: 140.0,
pinned: true,
),
SliverFillRemaining(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 8,
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
),
child: Padding(
padding: EdgeInsets.only(
left: 18.0,
top: 18.0,
),
child: Row(
children: <Widget>[
Text(
"Account",
style: TextStyle(
color: Colors.blue[700],
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
Container(
decoration: BoxDecoration(
color: Colors.white,
),
child: ListTile(
onTap: () {},
contentPadding: EdgeInsets.only(left: 18.0),
title: Text(
"+${snapshot.data['countryCode']} ${snapshot.data['phoneNumber']}",
style: TextStyle(fontSize: 16),
),
subtitle: Row(
children: <Widget>[
Text(
"Phone Number",
style: TextStyle(
fontSize: 12,
),
),
],
),
),
),
],
),
),
],
),
),
],
),
],
),
);
},
);
}
}
but this error happened
I/flutter ( 8691): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8691): The following NoSuchMethodError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state:
I/flutter ( 8691): _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#7db43):
I/flutter ( 8691): The method '[]' was called on null.
I/flutter ( 8691): Receiver: null
I/flutter ( 8691): Tried calling: []("countryCode")
I/flutter ( 8691):
I/flutter ( 8691): When the exception was thrown, this was the stack:
I/flutter ( 8691): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 8691): #1 _SettingsPageState.build.<anonymous closure> (package:silkwallet/page/settings.dart:81:54)
I/flutter ( 8691): #2 StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 8691): #3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 8691): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 8691): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 8691): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11)
I/flutter ( 8691): #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 8691): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #15 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11)
I/flutter ( 8691): #16 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #17 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #18 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #19 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4860:14)
I/flutter ( 8691): #20 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8691): #22 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 8691): #23 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8691): #24 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 8691): #25 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 8691): #26 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8691): #27 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
.
.
.
I/flutter ( 8691): #135 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 8691): #136 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 8691): #137 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 8691): #138 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 8691): #139 _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 8691): #140 _drawFrame (dart:ui/hooks.dart:143:3)
2- After some research for this error, I add connectionState condition inside StreamBuilder which solved above problem
this is the new code, i put the Scaffold inside active connectionState
class _SettingsPageState extends State<SettingsPage> {
ScrollController _scrollController;
#override
void initState() {
super.initState();
_scrollController = new ScrollController();
_scrollController.addListener(() => setState(() {}));
}
#override
void dispose() {
_scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: Shared.firestore.collection('client').document(Shared.firebaseUser.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
return Scaffold(
backgroundColor: Colors.grey[50],
body: Stack(
.
.
.
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Container(child: Center(child: CircularProgressIndicator()));
} else {
return Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(Icons.warning),
),
Text('Error in loadind data')
],
),
);
}
},
);
}
}
and I realized that when I scrolled the connectionState will change to waiting and the ScrollController not working under this state as shown in the image below
ScrollController: page keep flashing when try to scroll
The reason I want to use the ScrollController because I want to add FloatingActionButton inside Positioned which will scroll along & disappear when reach certain position, here's the image with FloatingActionButton
NoSuchMethodError the method was called on null errors are usually thrown when the method that you're trying to call from the object is yet to be initialized. The error seems to be coming from snapshot.data['countryCode']. What you can do here is add a null-check on snapshot before displaying the data.
if (snapshot != null && snapshot.hasData) {
// Display data
} else {
// Display circular progress...
}
I have an app which exports a json object to a json file and while it's exporting, I wanted to show an alert dialog with a circular progress indicator on it. But for some reason, the alert dialog with my progress indicator is not showing up.
This is the look of my app before I export my json:
Here is the code for activating the exporting part:
...
child: FlatButton(
onPressed: () async{
//Popping the confirm dialog
Navigator.pop(context);
//Showing the progress dialog
showProcessingDialog();
//Buying some time
_timer = Timer(Duration(seconds: 5), exportData);
//Pops the progress dialog
Navigator.pop(context);
//Shows the finished dialog
showFinishedDialog();
},
child: Text(
"Yes",
...
After I click 'Yes' in this alert button, it should show the progress dialog but it doesn't show, instead it shows the finished dialog.
Like this:
Here is the code for progress dialog:
void showProcessingDialog() async{
return showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context){
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
contentPadding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
content: Container(
width: 250.0,
height: 100.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
CircularProgressIndicator(),
Text("Exporting...",
style: TextStyle(
fontFamily: "OpenSans",
color: Color(0xFF5B6978)
)
)
]
)
)
);
}
);
}
Here is the exportData callback:
void exportData() async{
List<dynamic> _msgList = await _msgStorage._getList;
await _expData._saveList(_msgList);
}
I have tried to add Timer class to delay showing finished dialog for 3 seconds but it doesn't work. I can confirm that my json file was exported successfully but the callback of Timer which is the progress dialog didn't show up.
I would appreciate any kind of help.
UPDATE:
I rewrote my code based on the answer of diegoveloper:
onPressed: () async{
Navigator.pop(context);
print("confirm dialog has pop");
print("showing processdialog");
showProcessingDialog();
print("processdialog is being shown.");
print("buying some time");
await Future.delayed(Duration(seconds: 5));
print("done buying some time");
print("exporting begin");
await exportData();
print("exporting done");
Navigator.pop(context);
print("processdialog has pop");
print("showing finished dialog");
showFinishedDialog();
print("finished dialog is being shown.");
},
At this point, the process dialog is being shown but after printing the "exporting done" and executing the Navigator.pop(context); it gave an error and the process dialog remains in the screen, unpopped.
Like this:
I/flutter ( 9767): confirm dialog has pop
I/flutter ( 9767): showing processdialog
I/flutter ( 9767): processdialog is being shown.
I/flutter ( 9767): buying some time
I/flutter ( 9767): done buying some time
I/flutter ( 9767): exporting begin
I/flutter ( 9767): exporting done
E/flutter ( 9767): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 9767): Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 9767): At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
After I comment out the await Future.delayed(Duration(seconds: 5)); it worked fine.
My question is why did it failed when using Future.delayed?
Here is the full error:
I/flutter ( 9767): confirm dialog has pop
I/flutter ( 9767): showing processingdialog
I/flutter ( 9767): processdialog is being shown.
I/flutter ( 9767): buying some time
I/flutter ( 9767): done buying some time
I/flutter ( 9767): exporting begin
I/flutter ( 9767): exporting done
E/flutter ( 9767): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 9767): Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 9767): At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter ( 9767):
E/flutter ( 9767): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3246:9)
E/flutter ( 9767): #1 Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3255:6)
E/flutter ( 9767): #2 Element.ancestorStateOfType (package:flutter/src/widgets/framework.dart:3303:12)
E/flutter ( 9767): #3 Navigator.of (package:flutter/src/widgets/navigator.dart:1288:19)
E/flutter ( 9767): #4 ChatWindow.showExportedDialog.<anonymous closure>.<anonymous closure> (package:msgdiary/main.dart:368:37)
E/flutter ( 9767): <asynchronous suspension>
E/flutter ( 9767): #5 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter ( 9767): #6 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter ( 9767): #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter ( 9767): #8 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter ( 9767): #9 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
E/flutter ( 9767): #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
E/flutter ( 9767): #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter ( 9767): #12 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter ( 9767): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
E/flutter ( 9767): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter ( 9767): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter ( 9767): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter ( 9767): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter ( 9767): #18 _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter ( 9767): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
UPDATE:
It was my fault. I need to study more about context. It seems that I was popping the same context for the two dialogs. I changed the name of the dialog and it worked.
Why don't you extract it to a custom dialog widget and handle its states dynamically? It's cleaner and more customizable, also giving a timer (like you did of 5 seconds) it's not a good practice since you can't be sure how much time it will take to do its work.
Then I can suggest, for example, to create an enum DialogState with 3 states
enum DialogState {
LOADING,
COMPLETED,
DISMISSED,
}
Then create your own Dialog widget that when built receives its current state
class MyDialog extends StatelessWidget {
final DialogState state;
MyDialog({this.state});
#override
Widget build(BuildContext context) {
return state == DialogState.DISMISSED
? Container()
: AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
),
content: Container(
width: 250.0,
height: 100.0,
child: state == DialogState.LOADING
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
"Exporting...",
style: TextStyle(
fontFamily: "OpenSans",
color: Color(0xFF5B6978),
),
),
)
],
)
: Center(
child: Text('Data loaded with success'),
),
),
);
}
}
and then, in your screen, you can insert it anywhere you want. I changed my exportData function to dummy a request that takes 5 seconds.
class MyScreen extends StatefulWidget {
_MyScreenState createState() => _MyScreenState();
}
class _MyScreenState extends State<MyScreen> {
DialogState _dialogState = DialogState.DISMISSED;
void _exportData() {
setState(() => _dialogState = DialogState.LOADING);
Future.delayed(Duration(seconds: 5)).then((_) {
setState(() => _dialogState = DialogState.COMPLETED);
Timer(Duration(seconds: 3), () => setState(() => _dialogState = DialogState.DISMISSED));
});
}
#override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Stack(
alignment: Alignment.center,
children: <Widget>[
RaisedButton(
child: Text('Show dialog'),
onPressed: () => _exportData(),
),
MyDialog(
state: _dialogState,
)
],
),
),
);
}
}
You can do the following:
onPressed: () async{
//Popping the confirm dialog
Navigator.pop(context);
//Showing the progress dialog
showProcessingDialog();
//wait 5 seconds : just for testing purposes, you don't need to wait in a real scenario
await Future.delayed(Duration(seconds: 5));
//call export data
await exportData();
//Pops the progress dialog
Navigator.pop(context);
//Shows the finished dialog
await showFinishedDialog();
},
I am getting the following error when beginning to implement the camera plugin on my flutter app:
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method init on channel plugins.flutter.io/camera)
#0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:153:7)
<asynchronous suspension>
#1 _channel (package:camera/camera.dart:7:5)
#2 _channel (package:camera/camera.dart:6:21)
#3 availableCameras (package:camera/camera.dart:42:41)
<asynchronous suspension>
#4 main (file:///Users/waynerumble/Desktop/scott_and_viki/lib/main.dart:10:19)
<asynchronous suspension>
#5 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#6 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method list on channel plugins.flutter.io/camera)
#0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:153:7)
<asynchronous suspension>
#1 availableCameras (package:camera/camera.dart:42:50)
<asynchronous suspension>
#2 main (file:///Users/waynerumble/Desktop/scott_and_viki/lib/main.dart:10:19)
<asynchronous suspension>
#3 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
The error doesn't occur until i start using the plugin itself, i.e. if i replace Future<null> main() etc with void main() => runApp(new App()); the app runs fine. I've followed install instructions from the link provided and tried pasting in all the example incode in place of mine but still get the errors
My main.dart:
import 'package:flutter/material.dart';
import 'Localisations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'dart:async';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
Future<Null> main() async {
cameras = await availableCameras();
runApp(new App());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
var statusBarHeight = MediaQuery.of(context).padding.top;
var titleText = new Text(Localize.of(context).appTitle,
textAlign: TextAlign.center,
style: new TextStyle(fontFamily: 'CallingAngelsPersonalUse',
fontSize: 50.0,
color: Colors.black)
);
var backgroundImage = new BoxDecoration(
image: new DecorationImage(
image: new AssetImage('assets/background.png'),
fit: BoxFit.cover,
),
);
var mainContainer = new Container(
padding: EdgeInsets.only(top: statusBarHeight),
height: double.infinity,
width: double.infinity,
decoration: backgroundImage,
child: new Column(
children: <Widget>[
new Container(
margin: EdgeInsets.only(top: 10.0),
child: titleText
)
],
),
);
return new Scaffold(
body: mainContainer,
);
}
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
onGenerateTitle: (BuildContext context) => Localize.of(context).appTitle,
localizationsDelegates: [
const LocalizeDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', '')
],
home: new MyApp(),
);
}
}
My pubspec.yml:
dependencies:
flutter:
sdk: flutter
camera: ^0.1.2
path_provider: ^0.4.0
flutter_localizations:
sdk: flutter
This is my first real flutter app so any help would be appreciated.
Thanks
first check your app.build minSdkVersion.make sure minSdkVersion is 21.
minSdkVersion 21
here code example.
List<CameraDescription> cameras = [];
main() async{
WidgetsFlutterBinding.ensureInitialized();
try {
cameras = await availableCameras();
} on CameraException catch (e) {
logError(e.code, e.description);
}
runApp(MyApp());
}