Unable to Load Asset (flutter in android studio) - flutter

So my ball images are showing up on my emulator but not my magic.jpg that I added myself. My pubspec.yaml is fine. I know. Does anyone know what's wrong?
my folder tree
pubspec.yaml file:
name: magic_8_ball
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/magic.jpg
my code:
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: BallPage(),
),
);
class BallPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue[900],
title: Text('Ask Me Anything'),
),
body: Stack(children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/magic"),
fit: BoxFit.cover,
),
),
),
Ball()
]),
);
}
}
class Ball extends StatefulWidget {
#override
_BallState createState() => _BallState();
}
class _BallState extends State<Ball> {
int ballNum = 1;
#override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
onPressed: () {
setState(() {
ballNum = Random().nextInt(5) + 1;
});
},
child: Image.asset('assets/images/ball$ballNum.png')));
}
}
error log:
I/flutter (22530): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
I/flutter (22530): The following assertion was thrown resolving an image codec:
I/flutter (22530): Unable to load asset: assets/images/magic
I/flutter (22530):
I/flutter (22530): When the exception was thrown, this was the stack:
I/flutter (22530): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
I/flutter (22530): <asynchronous suspension>
I/flutter (22530): #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:464:44)
I/flutter (22530): <asynchronous suspension>
I/flutter (22530): #2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:449:14)
I/flutter (22530): #3 ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:316:48)
I/flutter (22530): #4 ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:160:22)
I/flutter (22530): #5 ImageProvider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:316:25)
I/flutter (22530): (elided 13 frames from package dart:async)
I/flutter (22530):
I/flutter (22530): Image provider: AssetImage(bundle: null, name: "assets/images/magic")
I/flutter (22530): Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#77a87(), name: "assets/images/magic",
I/flutter (22530): scale: 1.0)
I/flutter (22530): ════════════════════════════════════════════════════════════════════════════════════════════════════
Thanks a bunch!!
what my app looks like (as you can see, any ball image can show up, but not my background image, which I called magic.jpg

You didn't put the extension for the image magic in the widget AssetImage.
Simply, put it like this AssetImage("assets/images/magic.jpg") and it should work fine.

Related

How to play sound with package audioplayers in flutter

I'm doing course on flutter. I was trying to play sound in flutter.
Sadly, I'm having below error code
Here is my complete code
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() => runApp(XylophoneApp());
class XylophoneApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: TextButton(
onPressed: () async {
final player=AudioPlayer();
await player.play(AssetSource('sounds/note1.wav'));
},
child: const Text('Click Me'))),
),
),
);
}
}
Here is my pubspec.yaml file settings
dependencies:
audioplayers: ^1.1.1
assets:
- sounds/
Here is my errors:
****[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: assets/sounds/note1.wav
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:258:7)
<asynchronous suspension>
#1 AudioCache.fetchToMemory (package:audioplayers/src/audio_cache.dart:75:22)
<asynchronous suspension>
#2 AudioCache.load (package:audioplayers/src/audio_cache.dart:101:31)
<asynchronous suspension>
#3 AudioPlayer.setSourceAsset (package:audioplayers/src/audioplayer.dart:237:17)
<asynchronous suspension>
#4 AudioPlayer.play (package:audioplayers/src/audioplayer.dart:123:5)
<asynchronous suspension>
#5 XylophoneApp.build.<anonymous closure> (package:xylophone1/main.dart:16:21)
<asynchronous suspension>****
I just need to play sound with this audio player package.
I've changed pubspec.yaml settings and folder name "assets"
I also changed source this line to await "player.play(AssetSource('note1.wav'));"

Flutter -- No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

I'm learning Flutter by following the relatively recent tutorial (made in February - LINK) and while I wrote the same code as author I'm getting the following exception:
======== Exception caught by widgets library =======================================================
The following FirebaseException was thrown building FutureBuilder<FirebaseApp>(dirty, state: _FutureBuilderState<FirebaseApp>#881ee):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
FutureBuilder<FirebaseApp> FutureBuilder:file:///C:/Users/Mrky/Desktop/Sve/Faks/10_semestar/mynotes/lib/main.dart:30:13
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:173:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:53:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:38:47)
#3 HomePage.build.<anonymous closure> (package:mynotes/main.dart:37:34)
#4 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:615:55)
#5 StatefulElement.build (package:flutter/src/widgets/framework.dart:4919:27)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4806:15)
#7 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4977:11)
#8 Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#9 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#10 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:891:21)
#11 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:370:5)
#12 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1146:15)
#13 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1083:9)
#14 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:997:5)
#18 _invoke (dart:ui/hooks.dart:151:10)
#19 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#20 _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
==========================================================================================
The code that I have currently written is:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:mynotes/firebase_options.dart';
import 'package:mynotes/views/login_view.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const HomePage(),
),
);
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: FutureBuilder(
future: Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
print(FirebaseAuth.instance.currentUser);
return const Text('Done');
default:
return const Text('Loading...');
}
},
),
);
}
}
As it is visible I have Firebase.initializeApp inside future of FutureBuilder. Also If I comment out the line print(FirebaseAuth.instance.currentUser); the app will show text Done without any problem.
Run flutter clean, then add the dart pub package firebase_core with the command flutter pub add firebase_core. Finally, run flutter pub get to resolve all the dependencies.
Make your void function async and add the following lines inside your void main.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}

Looking up a deactivated widget's ancestor is unsafe. The relevant error-causing widget was Consumer<ShowHomeProvider>

After updating flutter to the latest version, when i push the MesSuivisPage widget, igot this error:
FlutterError (Looking up a deactivated widget's ancestor is unsafe.
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 dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)
This is the navigationpage:
import 'package:bam_mobile/src/provider/animation_provider.dart';
import 'package:bam_mobile/src/provider/current_exlusive_code.dart';
import 'package:bam_mobile/src/provider/home_provider.dart';
import 'package:bam_mobile/src/provider/product_somme.dart';
import 'package:bam_mobile/src/provider/selected_agence_provider.dart';
import 'package:bam_mobile/src/provider/selected_embalage.dart';
import 'package:bam_mobile/src/provider/showHomeProvider.dart';
import 'package:bam_mobile/src/provider/showpages_provider.dart';
import 'package:bam_mobile/src/provider/tarif_provider.dart';
import 'package:bam_mobile/src/services/suivis_historic_status_handler.dart';
import 'package:bam_mobile/src/shared/global_context.dart';
import 'package:bam_mobile/src/shared/styles.dart';
import 'package:bam_mobile/src/ui/views/agences_page.dart';
import 'package:bam_mobile/src/ui/views/home_page.dart';
import 'package:bam_mobile/src/ui/views/mes_suivis_page.dart';
import 'package:bam_mobile/src/ui/views/promos_page.dart';
import 'package:bam_mobile/src/ui/views/spalsh_screen.dart';
import 'package:bam_mobile/src/ui/views/tarifs_page.dart';
import 'package:bam_mobile/src/ui/widgets/animation_navigation.dart';
import 'package:bam_mobile/src/ui/widgets/custom_app_bar.dart';
import 'package:bam_mobile/src/ui/widgets/custom_bottom_bar.dart';
import 'package:bam_mobile/src/ui/widgets/custom_floating_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'package:loading/loading.dart';
import 'package:provider/provider.dart';
import 'config_size.dart';
class CustomNavigation extends StatefulWidget {
final bool toSuivisHistorique;
CustomNavigation({this.toSuivisHistorique = false});
#override
_CustomNavigationState createState() => _CustomNavigationState();
}
class _CustomNavigationState extends State<CustomNavigation>
with TickerProviderStateMixin {
TabController _tabController;
AnimationController splashAnimationController;
#override
void initState() {
super.initState();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.transparent),
);
settingAnimtion();
_tabController = TabController(vsync: this, length: 4);
_tabController.addListener(listenToAnimation);
gotoNextPage();
WidgetsBinding.instance.addPostFrameCallback(initTabController);
SuivisHistoricHandler historicHandler = new SuivisHistoricHandler();
historicHandler.runHandler();
}
initTabController(_) {
AnimationProvider animationProvider = Provider.of(context, listen: false);
animationProvider.tabController = _tabController;
}
listenToAnimation() {
if (_tabController.index == 2) setState(() {});
}
settingAnimtion() {
splashAnimationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 1300),
);
}
listenSplashAnimtion() {
if (splashAnimationController.isCompleted) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
overlays: SystemUiOverlay.values);
splashAnimationController?.removeListener(listenSplashAnimtion);
splashAnimationController?.dispose();
}
}
#override
dispose() {
_tabController.dispose();
super.dispose();
}
Future<void> gotoNextPage() async {
await Future.delayed(Duration(seconds: 6));
splashAnimationController.forward();
splashAnimationController.addListener(listenSplashAnimtion);
}
#override
Widget build(BuildContext context) {
ConfigSize.init(context);
ConfigSize.init(context);
ScreenUtil.init(context, minTextAdapt: true, deviceSize: Size(414, 785));
GlobalContext.init(context);
print(MediaQuery.of(context).size.width);
return Material(
child: Stack(
children: <Widget>[
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => SelectedEmbalageProvider(),
),
ChangeNotifierProvider(
create: (_) => TarifProvider(),
),
ChangeNotifierProvider(
create: (_) => ProductSomme(),
),
ChangeNotifierProvider(
create: (_) => CurrentExlusiveCodeProvider(),
),
ChangeNotifierProvider(
create: (_) => SelectedAgenceProvider(),
),
],
child: WillPopScope(
onWillPop: () async => false,
child: Stack(
children: <Widget>[
Scaffold(
backgroundColor: CustomColor.background,
body: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
pages(),
Consumer<ShowPageProvider>(
builder: (_, status, __) {
return status.animationStatus ==
AnimationStatus.forward
? AnimatedContainer(
duration: Duration(milliseconds: 400),
decoration: BoxDecoration(
gradient: status.animationStatus ==
AnimationStatus.forward
? RadialGradient(
colors: [
Colors.black,
Colors.transparent
.withOpacity(0.7),
],
center:
FractionalOffset(0.5, 0.85),
)
: null,
),
)
: SizedBox();
},
),
Consumer<ShowPageProvider>(
builder: (_, provider, __) {
return provider.animationStatus ==
AnimationStatus.dismissed
? SizedBox()
: AnimationNavigation();
},
),
MediaQuery.of(context).viewInsets.bottom > 0
? SizedBox()
: CustomBottomBar(
tabController: _tabController,
),
MediaQuery.of(context).viewInsets.bottom > 0
? SizedBox()
: CustomFloatingButton(),
],
),
),
Consumer<HomeProvider>(
builder: (_, HomeProvider homeProvider, __) {
if (homeProvider.musees.isEmpty ||
homeProvider.notificationsList.isEmpty)
return Container(
width: ScreenUtil().screenWidth,
height: ScreenUtil().screenHeight,
color: Colors.transparent.withOpacity(0.5),
child: Center(
child: Loading(
indicator: BallPulseIndicator(),
color: CustomColor.yellow,
),
),
);
return SizedBox();
},
),
],
),
),
),
AnimatedBuilder(
animation: splashAnimationController,
builder: (_, __) {
print(splashAnimationController.value);
return Transform.translate(
offset: Offset(
-ScreenUtil().screenWidth * splashAnimationController.value,
0,
),
child: SplashScreen(),
);
}),
],
),
);
}
SizedBox pages() {
return SizedBox(
height: (_tabController.index == 0 && ScreenUtil().screenHeight > 850)
? ScreenUtil().screenHeight * 1.35
: ScreenUtil().screenHeight,
child: Stack(
children: <Widget>[
Consumer<ShowHomeProvider>(
builder: (_, provider, widget) {
if (provider.showHome) return HomePage();
return TabBarView(
physics: NeverScrollableScrollPhysics(),
controller: _tabController,
children: <Widget>[
MesSuivisPage(),
PromosPage(),
TarifsPage(),
AgencesPage(),
],
);
},
),
CustomAppBar(
height: ScreenUtil().setSp(93),
tabController: _tabController,
),
],
),
);
}
}
class AnimatedMenuItems {
final String svg;
final Color color;
final String label;
final double x;
final double y;
final int index;
const AnimatedMenuItems(
{this.x, this.y, this.label, this.svg, this.color, this.index});
}
const List<AnimatedMenuItems> animatedMenuItems = const [
AnimatedMenuItems(
label: "COURRIER",
color: CustomColor.yellow,
svg: "assets/icons/menu/courrier.svg",
x: -36,
y: 110,
index: 0,
),
AnimatedMenuItems(
label: "COLIS",
color: Color(0xffFF7600),
svg: "assets/icons/menu/colis.svg",
x: 37,
y: 170,
index: 1,
),
AnimatedMenuItems(
label: "NOS PRODUITS",
color: Color(0xff46BA83),
svg: "assets/icons/menu/produits.svg",
x: 126,
y: 197,
index: 2,
),
AnimatedMenuItems(
label: "DIGITAL",
color: Color(0xff2800E7),
svg: "assets/icons/menu/digital.svg",
x: 212,
y: 170,
index: 3,
),
];
And This is the consol ouput:
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Consumer<ShowHomeProvider>(dirty, dependencies: [_InheritedProviderScope<ShowHomeProvider?>]):
Looking up a deactivated widget's ancestor is unsafe.
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 dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
The relevant error-causing widget was
Consumer<ShowHomeProvider>
When the exception was thrown, this was the stack
#0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
#1 Element._debugCheckStateIsActiveForAncestorLookup
#2 Element.getElementForInheritedWidgetOfExactType
#3 debugCheckHasMediaQuery.<anonymous closure>
#4 debugCheckHasMediaQuery
#5 MediaQuery.of
#6 ScreenUtil.screenWidth
#7 ScreenUtil.scaleWidth
#8 ScreenUtil.scaleText
#9 ScreenUtil.setSp
#10 CustomBottomBar.build.<anonymous closure>
#11 Consumer.buildWithChild
#12 SingleChildStatelessWidget.build
#13 StatelessElement.build
#14 SingleChildStatelessElement.build
#15 ComponentElement.performRebuild
#16 Element.rebuild
#17 BuildOwner.buildScope
#18 WidgetsBinding.drawFrame
#19 RendererBinding._handlePersistentFrameCallback
#20 SchedulerBinding._invokeFrameCallback
#21 SchedulerBinding.handleDrawFrame
#22 SchedulerBinding._handleDrawFrame
#26 _invoke (dart:ui/hooks.dart:151:10)
#27 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#28 _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
════════════════════════════════════════════════════════════════════════════════
Restarted application in 11 049ms.
════════ Exception caught by widgets library ═══════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
The relevant error-causing widget was
Consumer<ShowHomeProvider>
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
The relevant error-causing widget was
Consumer<ShowHomeProvider>
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
The relevant error-causing widget was
MesSuivisPage
════════════════════════════════════════════════════════════════════════════════
I/flutter ( 6351): init called
I/flutter ( 6351): 411.42857142857144
I/flutter ( 6351): getNotification api entre d
I/flutter ( 6351): getProducts api entred
I/flutter ( 6351): init called
I/Choreographer( 6351): Skipped 88 frames! The application may be doing too much work on its main thread.
I/flutter ( 6351): 0.0
I/flutter ( 6351): Entred getAgences : param null null
I/flutter ( 6351): getProduits api entred
I/flutter ( 6351): init called
I/OpenGLRenderer( 6351): Davey! duration=1767ms; Flags=1, IntendedVsync=21194800748633, Vsync=21194800748633, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=21194805459600, AnimationStart=21194805479500, PerformTraversalsStart=21194805506500, DrawStart=21196288226200, SyncQueued=21196288632200, SyncStart=21196289648100, IssueDrawCommandsStart=21196289828900, SwapBuffers=21196386491200, FrameCompleted=21196568869600, DequeueBufferDuration=275700, QueueBufferDuration=1393800, GpuCompleted=16410097190600,
I/flutter ( 6351): ********** the controller is intialized************
I/flutter ( 6351): AnimationProvider(_menuPositionValues: 0.0, _popPage: false, _pageContext: null, globalContext: null, _flareAnimation: remove_to_add, _flareAnimationCompleted: true, _animationController: null, initializeProvider: true, tabController: Instance of 'TabController')
I/flutter ( 6351): init called
I/flutter ( 6351): 411.42857142857144
I/flutter ( 6351): 0.0
I/flutter ( 6351): init called
I/flutter ( 6351): init called
I/flutter ( 6351): 0.0
I/flutter ( 6351): init called
I/flutter ( 6351): 0.2820923076923077
I/flutter ( 6351): init called
I/flutter ( 6351): 0.3589376923076923
I/flutter ( 6351): init called
I/flutter ( 6351): 0.39738615384615383
I/flutter ( 6351): init called
I/flutter ( 6351): 0.4486838461538461
I/flutter ( 6351): init called
I/flutter ( 6351): 0.5127876923076923
I/flutter ( 6351): init called
I/flutter ( 6351): 0.5513707692307692
I/flutter ( 6351): init called
I/flutter ( 6351): 0.60252
I/flutter ( 6351): init called
I/flutter ( 6351): 0.6410030769230769
I/flutter ( 6351): init called
I/flutter ( 6351): 0.6794476923076923
I/flutter ( 6351): init called
I/flutter ( 6351): 0.7050869230769231
I/flutter ( 6351): init called
I/flutter ( 6351): 0.7307615384615385
I/flutter ( 6351): init called
I/flutter ( 6351): 0.75639
I/flutter ( 6351): init called
I/flutter ( 6351): 0.7820484615384616
I/flutter ( 6351): init called
I/flutter ( 6351): 0.8076692307692308
I/flutter ( 6351): init called
I/flutter ( 6351): 0.8333638461538461
I/flutter ( 6351): init called
I/flutter ( 6351): 0.8589538461538462
I/flutter ( 6351): init called
I/flutter ( 6351): 0.8846107692307692
I/flutter ( 6351): init called
I/flutter ( 6351): 0.9230638461538462
I/flutter ( 6351): init called
I/flutter ( 6351): 0.9358830769230768
I/flutter ( 6351): init called
I/flutter ( 6351): 0.9743561538461539
I/flutter ( 6351): init called
I/flutter ( 6351): 0.9871830769230769
I/flutter ( 6351): init called
I/flutter ( 6351): 1.0
I/flutter ( 6351): init called
I/flutter ( 6351): init called
I/flutter ( 6351): 411.42857142857144
I/flutter ( 6351): 1.0
I/flutter ( 6351): init called
I/flutter ( 6351): init called
Does anyone know what is wrong ?
Thank you

Flutter program was running before, no changes were made, it does't run anymore

This is my code and the error I'm getting in Visual Studio Code. It used to work before, not sure if an update messed it up. I have other Flutter programs running just fine, not sure what the problem is with this one.
// 1) Create a new Flutter App (in this project) and output an AppBar and some text
// below it
// 2) Add a button which changes the text (to any other text of your choice)
// 3) Split the app into three widgets: App, TextControl & Text
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
Random _stringIndex = new Random();
var _randomStringIndex;
final _strings = const [
"Hello",
"This is a string",
"This is random",
];
void _changeText() {
setState(() {
_randomStringIndex = _stringIndex.nextInt(_strings.length);
});
print(_strings[_randomStringIndex]);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: _changeText,
),
Text(
_strings[_randomStringIndex],
),
],
),
),
),
),
);
}
}
Launching lib/main.dart on Android SDK built for x86 in debug mode...
✓ Built build/app/outputs/apk/debug/app-debug.apk. Connecting to VM
Service at ws://127.0.0.1:40605/I0TqLbk5jw4=/ws D/EGL_emulation(
7151): eglMakeCurrent: 0xe1b1a3c0: ver 2 0 (tinfo 0xe1b0f770)
D/eglCodecCommon( 7151): setVertexArrayObject: set vao to 0 (0) 1 0
I/flutter ( 7151): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════ I/flutter
( 7151): The following ArgumentError was thrown building MyApp(dirty,
state: _MyAppState#202c3): I/flutter ( 7151): Invalid argument(s)
I/flutter ( 7151): I/flutter ( 7151): The relevant error-causing
widget was: I/flutter ( 7151): MyApp I/flutter ( 7151):
package:flutter_assignment/main.dart:11 I/flutter ( 7151): I/flutter (
7151): When the exception was thrown, this was the stack: I/flutter (
7151): #0 List.[] (dart:core-patch/array.dart:169:52) I/flutter
( 7151): #1 _MyAppState.build
package:flutter_assignment/main.dart:57 I/flutter ( 7151): #2
StatefulElement.build package:flutter/…/widgets/framework.dart:4619
I/flutter ( 7151): #3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4502 I/flutter ( 7151): #4
StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4675 I/flutter ( 7151): #5
Element.rebuild package:flutter/…/widgets/framework.dart:4218
I/flutter ( 7151): #6 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4481 I/flutter ( 7151): #7
StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4666 I/flutter ( 7151): #8
ComponentElement.mount package:flutter/…/widgets/framework.dart:4476
I/flutter ( 7151): #9 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3446 I/flutter ( 7151): #10
Element.updateChild package:flutter/…/widgets/framework.dart:3214
I/flutter ( 7151): #11 RenderObjectToWidgetElement._rebuild
package:flutter/…/widgets/binding.dart:1148 I/flutter ( 7151): #12
RenderObjectToWidgetElement.mount
package:flutter/…/widgets/binding.dart:1119 I/flutter ( 7151): #13
RenderObjectToWidgetAdapter.attachToRenderTree.
package:flutter/…/widgets/binding.dart:1061 I/flutter ( 7151): #14
BuildOwner.buildScope package:flutter/…/widgets/framework.dart:2607
I/flutter ( 7151): #15
RenderObjectToWidgetAdapter.attachToRenderTree
package:flutter/…/widgets/binding.dart:1060 I/flutter ( 7151): #16
WidgetsBinding.attachRootWidget
package:flutter/…/widgets/binding.dart:941
You can copy paste run full code below
You need to init _randomStringIndex
code snippet
var _randomStringIndex = 0;
working demo
full code
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
Random _stringIndex = new Random();
var _randomStringIndex = 0;
final _strings = const [
"Hello",
"This is a string",
"This is random",
];
void _changeText() {
setState(() {
_randomStringIndex = _stringIndex.nextInt(_strings.length);
});
print(_strings[_randomStringIndex]);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: _changeText,
),
Text(
_strings[_randomStringIndex],
),
],
),
),
),
),
);
}
}
Try to run this command inside your project (terminal):
flutter clean
and then run it again!

Can't understand the problem. Button not working properly

I follow the steps of a packpub intermediate course, and the code does not work properly. I need some help to understand the Exception.
The following assertion was thrown while handling a gesture:
type 'List<dynamic>' is not a subtype of type 'List<PopupMenuEntry<Animals>>'
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_State createState() => new _State();
}
enum Animals{Cat, Dog, Bird, Lizard, Fish}
class _State extends State<MyApp> {
Animals _selected = Animals.Cat;
String _value = 'Make a Selection';
List _items = new List();
#override
void initState() {
for(Animals animal in Animals.values) {
_items.add(new PopupMenuItem(
child: new Text(_getDisplay(animal),),
value: animal,
));
}
}
void _onSelected(Animals animal){
setState((){
_selected = animal;
_value = 'You Selected ${_getDisplay(animal)}';
});
}
String _getDisplay(Animals animal) {
int index = animal.toString().indexOf('.');
index++;
return animal.toString().substring(index);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Name here'),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Center(
child: new Row(
children: <Widget>[
new Container(
padding: new EdgeInsets.all(5.0),
child: new Text(_value),
),
new PopupMenuButton<Animals>(
child: new Icon(Icons.input),
initialValue: Animals.Cat,
onSelected: _onSelected,
itemBuilder: (BuildContext context) {
return _items;
}
)
],
),
),
),
);
}
}
When I press the PopupMenuButton the list does not appear,
and this is what I get on the console:
I/flutter (10194): ══╡ EXCEPTION CAUGHT BY GESTURE ╞══════════════════════════════════════════════════════════════════
I/flutter (10194): The following assertion was thrown while handling a gesture: I/flutter (10194): type 'List' is not a subtype of type 'List>'
I/flutter (10194): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (10194): more information in this error message to help you determine and fix the underlying cause.
I/flutter (10194): In either case, please report this assertion by filing a bug on GitHub:
I/flutter (10194):
https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter (10194): When the exception was thrown, this was the stack:
I/flutter (10194): #0 _State.build. (package:widget4/main.dart:67:21)
I/flutter (10194): #1 _PopupMenuButtonState.showButtonMenu (package:flutter/src/material/popup_menu.dart:900:21)
I/flutter (10194): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
I/flutter (10194): #3 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:568:30)
I/flutter (10194): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:120:24)
I/flutter (10194): #5 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
I/flutter (10194): #6 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
I/flutter (10194): #7 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:369:9)
I/flutter (10194): #8 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
I/flutter (10194): #9 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
I/flutter (10194): #10
_WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:214:19)
I/flutter (10194): #11
_WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22)
I/flutter (10194): #12
_WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7)
I/flutter (10194): #13
_WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (10194): #14
_WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
I/flutter (10194): #18 _invoke1 (dart:ui/hooks.dart:223:10)
I/flutter (10194): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
I/flutter (10194): (elided 3 frames from package dart:async)
I/flutter (10194): Handler: onTap
I/flutter (10194): Recognizer:
I/flutter (10194): TapGestureRecognizer#7540f(debugOwner: GestureDetector, state: accepted, won arena, finalPosition:
I/flutter (10194): Offset(156.5, 334.8), sent tap down) ══════════════════════════════════════════════════════════════
I/flutter (10194): Another exception was thrown: type 'List' is not a subtype of type 'List>'