I created an animation using Flare for my Flutter project. But, I got an error when trying to Run it. The animation doesn't work and only a black screen with the logo i used shows.
Here is my code:
import 'package:flare_splash_screen/flare_splash_screen.dart';
import 'package:flutter/material.dart';
void main () {
runApp(MaterialApp(
home: SplashScreen(
'assets/splash.flr',
(context) => SplashTela(),
startAnimation: 'intro',
backgroundColor: Color(0xff3333),
),
));
}
class SplashTela extends StatefulWidget {
#override
_SplashTelaState createState() => _SplashTelaState();
}
class _SplashTelaState extends State<SplashTela> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: Container(
color: Colors.redAccent,
),
);
}
}
And here is the error:
E/flutter (25496): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception:
'package:flare_splash_screen/flare_splash_screen.dart': Failed assertion: line 113 pos 16: '!
(isLoading == null && until == null)': isLoading and until are null, pick one ;)
E/flutter (25496): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:40:39)
E/flutter (25496): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (25496): #2 new SplashScreen
(package:flare_splash_screen/flare_splash_screen.dart:113:16)
E/flutter (25496): #3 main (package:leagueuniverse/main.dart:6:11)
E/flutter (25496): #4 _runMainZoned.<anonymous closure>.<anonymous closure>
(dart:ui/hooks.dart:229:25)
E/flutter (25496): #5 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (25496): #6 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (25496): #7 _runZoned (dart:async/zone.dart:1516:10)
E/flutter (25496): #8 runZoned (dart:async/zone.dart:1500:12)
E/flutter (25496): #9 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
E/flutter (25496): #10 _startIsolate.<anonymous closure> (dart:isolate-
patch/isolate_patch.dart:305:19)
E/flutter (25496): #11 _RawReceivePortImpl._handleMessage (dart:isolate-
patch/isolate_patch.dart:172:12)
E/flutter (25496):
you need to pass until: () => Future.delayed(Duration(seconds: 5)),
or use isLoading demo code for isLoading https://github.com/jaumard/flare_splash_screen/blob/master/example/lib/isLoading.dart
an use SplashScreen.navigate
I use official example to test your case
code snippet
void main() {
runApp(MaterialApp(
home: SplashScreen.navigate(
name: 'assets/intro.flr',
next: (context) => SplashTela(),
startAnimation: '1',
backgroundColor: Color(0xff3333),
until: () => Future.delayed(Duration(seconds: 5)),
),
));
}
full test code work without error
import 'package:flare_splash_screen/flare_splash_screen.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: SplashScreen.navigate(
name: 'assets/intro.flr',
next: (context) => SplashTela(),
startAnimation: '1',
backgroundColor: Color(0xff3333),
until: () => Future.delayed(Duration(seconds: 5)),
),
));
}
class SplashTela extends StatefulWidget {
#override
_SplashTelaState createState() => _SplashTelaState();
}
class _SplashTelaState extends State<SplashTela> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: Container(
color: Colors.redAccent,
),
);
}
}
Related
Hello I was calling a startelection function from my flutter app on a button click and I got this error
the startelection function connects my flutter app with my solidity smart contract and starts the election through infura
I don't know why I am getting this error it was running fine before
error:
E/flutter (31094): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast
E/flutter (31094): #0 JsonRPC.call (package:web3dart/json_rpc.dart:53:27)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #1 Web3Client._makeRPCCall (package:web3dart/src/core/client.dart:54:20)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #2 Web3Client.getGasPrice (package:web3dart/src/core/client.dart:175:18)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #3 _fillMissingData (package:web3dart/src/core/transaction_signer.dart:36:16)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #4 Web3Client.signTransaction (package:web3dart/src/core/client.dart:316:26)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #5 Web3Client.sendTransaction (package:web3dart/src/core/client.dart:285:18)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #6 startElection (package:election/services/functions.dart:29:18)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094): #7 _HomeState.build.<anonymous closure> (package:election/pages/home.dart:53:25)
E/flutter (31094): <asynchronous suspension>
E/flutter (31094):
home.dart :
import 'package:election/utils/Constants.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';
import '../services/functions.dart';
import 'Electioninfo.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late Client? httpClient;
late Web3Client? ethclient;
TextEditingController controller = TextEditingController();
#override
void initState() {
httpClient = Client();
ethclient = Web3Client(infura_url, httpClient!);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Start Election'),
),
body: Container(
padding: const EdgeInsets.all(14),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: controller,
decoration: const InputDecoration(
filled: true, hintText: 'Enter election name'),
),
const SizedBox(
height: 10,
),
Container(
width: double.infinity,
height: 45,
child: ElevatedButton(
onPressed: () async {
if (controller.text.isNotEmpty) {
await startElection(controller.text, ethclient!);
if(!mounted)return;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ElectionInfo(
ethClient: ethclient!,
electionName: controller.text,
)));
}
},
child: const Text('Start Election')))
],
),
),
);
}
}
function.dart :
Future<String> startElection(String name,Web3Client ethclient) async{
var response = await callFunction('startElection', [name], ethclient, owner_private_key);
print("election started successfully");
return response;
}
Future<String> callFunction(String funcname,List<dynamic>args,Web3Client ethClient,String privateKey) async{
EthPrivateKey credentials = EthPrivateKey.fromHex(privateKey);
DeployedContract contract = await loadcontract();
final ethfunction = contract.function(funcname);
final result = ethClient.sendTransaction(
credentials,Transaction.callContract(contract: contract, function: ethfunction, parameters: args),
chainId: null,fetchChainIdFromNetworkId: true);
return result;
}
Please try with addding dart_web3: ^0.0.3 dependencies
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());
}
I am trying to take an image and send it to IBM Watson to classify it into one of 3 custom classifiers. Below is all my code.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ibm_watson/flutter_ibm_watson.dart';
import 'package:ibm_visual_recog_img_file/connection.dart';
import 'package:ourearth2020/screens/Community.dart';
import 'package:path/path.dart';
import 'dart:async';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:path_provider/path_provider.dart';
class VisualPage extends StatefulWidget {
#override
_VisualPageState createState() => _VisualPageState();
}
class _VisualPageState extends State<VisualPage> {
CameraController _controller;
List cameras;
String path;
var galleryImage;
CameraDescription cameraDescription;
Future initCamera() async {
cameras = await availableCameras();
var frontCamera = cameras.first;
_controller = CameraController(frontCamera, ResolutionPreset.high);
try {
await _controller.initialize();
} catch (e) {}
print('Controller Is Init:' + _controller.value.isInitialized.toString());
displayPreview();
}
bool displayPreview() {
if (_controller == null || !_controller.value.isInitialized) {
return false;
} else {
return true;
}
}
Future getImageFromGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
galleryImage = image;
});
print('GALLERY IMAGE' + galleryImage.toString());
return galleryImage;
}
#override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
print('Running');
initCamera();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(children: [
displayPreview()
? AspectRatio(
aspectRatio: MediaQuery.of(context).size.width /
MediaQuery.of(context).size.height,
child: CameraPreview(_controller),
)
: Container(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.yellow),
),
),
Positioned(
top: MediaQuery.of(context).size.height - 120,
child: GestureDetector(
onTap: () async {
await getImageFromGallery();
Navigator.push(context, MaterialPageRoute(builder: (context) =>
DisplayPicture(image: galleryImage)
));
},
child: Icon(
Icons.image,
color: Colors.white,
size: 60,
)),
),
Positioned(
top: MediaQuery.of(context).size.height - 120,
left: MediaQuery.of(context).size.width / 2.2,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
child: Container(
child: Icon(
Icons.camera,
color: Colors.white,
size: 60,
)),
onTap: () async {
final path = (await getTemporaryDirectory()).path +
'${DateTime.now()}.png';
try {
await _controller.takePicture(path);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DisplayPicture(imagePath: path)));
} catch (e) {
print('EEEE' + e);
}
}))
]));
}
}
class DisplayPicture extends StatelessWidget {
String imagePath;
File image;
String _text;
// File file = File(imagePath)
DisplayPicture({this.imagePath, this.image});
visualImageClassifier(File image) async{
IamOptions options = await IamOptions(iamApiKey: "NRDjngCby2d-pSHOPyWQJxhuB6vOY2uOTCX6KV2BCfwB", url: "https://api.us-south.visual-recognition.watson.cloud.ibm.com/instances/ef286f4e-84c7-44e0-b63d-a6a49a142a30").build();
VisualRecognition visualRecognition = new VisualRecognition(iamOptions: options, language: Language.ENGLISH); // Language.ENGLISH is language response
ClassifiedImages classifiedImages = await visualRecognition.classifyImageFile(image.path);
print(classifiedImages.getImages()[0].getClassifiers()[0]
.getClasses()[0]
.className);
// print("${image.toString()}");
// print('ACCESS'+options.accessToken);
//print(options);
//print("${image.path}");
//print('CLASSIFICATION'+classifiedImages.customClasses.toString()); // StreamBuilder(
// stream: StreamMyClassifier(
// image,
// 'NRDjngCby2d-pSHOPyWQJxhuB6vOY2uOTCX6KV2BCfwB', 'CompostxLandfillxRecycle_2056123069'),
// builder: (context, snapshot) {
// if (snapshot.hasData) {
// _text = snapshot.data;
// print(_text);
// }
// else {
// print('NO DATA AVAILABLE');
// }
//
// }
// );
}
#override
Widget build(BuildContext context) {
return Scaffold(body:Stack(children:[Center(child:image==null?Image.file(File(imagePath)):Image.file(image)),Positioned(
top: MediaQuery.of(context).size.height/2,
child: FloatingActionButton(onPressed:() async{
await visualImageClassifier(image==null?File(imagePath):image);
},
child:Icon(Icons.arrow_right)),
)]));
}
}
The image is successfully displayed on my screen but once I send it through the visualRecognition.classifyImageFile(....); it gives me an error saying I can not use image because it only supports String. I converted it to String but it gives me the error below.
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/data/user/0/com.example.ourearth2020/cache2020-09-17 18:50:16.530957.png'' (OS Error: No such file or directory, errno = 2)
E/flutter (17606): #0 _File.length.<anonymous closure> (dart:io/file_impl.dart:366:9)
E/flutter (17606): #1 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter (17606): #2 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (17606): #3 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter (17606): #4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter (17606): #5 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter (17606): #6 Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter (17606): #7 Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:567:7)
E/flutter (17606): #8 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (17606): #9 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (17606): #10 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (17606): #11 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (17606): #12 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (17606): #13 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter (17606):
Some of the questions I have: Can I get the confidence score using this? The last time I tried using those statements to classify the image it used a general classifier(if I input an image of a skyscraper it told me skyscraper) so how can I have it classify with my 3 classifiers?
Btw I already set up the IBM Cloud and it is fully functional. The library that I found from pub.dev is here https://pub.dev/packages/flutter_ibm_watson
EDIT error code for getImages() method
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The method 'getImages' was called on null.
E/flutter (31403): Receiver: null
E/flutter (31403): Tried calling: getImages()
E/flutter (31403): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (31403): #1 DisplayPicture.visualImageClassifier (package:ourearth2020/screens/VisualPage.dart:147:30)
E/flutter (31403): <asynchronous suspension>
E/flutter (31403): #2 DisplayPicture.build.<anonymous closure> (package:ourearth2020/screens/VisualPage.dart:177:15)
E/flutter (31403): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter (31403): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter (31403): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (31403): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (31403): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (31403): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter (31403): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter (31403): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter (31403): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter (31403): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (31403): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter (31403): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter (31403): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter (31403): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (31403): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (31403): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (31403): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (31403): #20 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (31403): #21 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (31403): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (31403): #23 _invoke1 (dart:ui/hooks.dart:283:10)
E/flutter (31403): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:192:5)
E/flutter (31403):
You can copy past run full code below
You can see confidence score in working demo below
please change image.toString() to image.path because image is File
from
ClassifiedImages classifiedImages = await visualRecognition.classifyImageFile(image.toString());
to
ClassifiedImages classifiedImages = await visualRecognition.classifyImageFile(image.path);
working demo
working demo 2 for CameraPreview
I/flutter (31132): living room
full code
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter_ibm_watson/flutter_ibm_watson.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
class VisualPage extends StatefulWidget {
#override
_VisualPageState createState() => _VisualPageState();
}
class _VisualPageState extends State<VisualPage> {
CameraController _controller;
List cameras;
String path;
var galleryImage;
CameraDescription cameraDescription;
Future initCamera() async {
cameras = await availableCameras();
var frontCamera = cameras.first;
_controller = CameraController(frontCamera, ResolutionPreset.high);
try {
await _controller.initialize();
} catch (e) {}
print('Controller Is Init:' + _controller.value.isInitialized.toString());
displayPreview();
setState(() {});
}
bool displayPreview() {
if (_controller == null || !_controller.value.isInitialized) {
return false;
} else {
return true;
}
}
Future getImageFromGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
galleryImage = image;
});
print('GALLERY IMAGE' + galleryImage.toString());
return galleryImage;
}
#override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
print('Running');
initCamera();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(children: [
displayPreview()
? AspectRatio(
aspectRatio: MediaQuery.of(context).size.width /
MediaQuery.of(context).size.height,
child: CameraPreview(_controller),
)
: Container(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.yellow),
),
),
Positioned(
top: MediaQuery.of(context).size.height - 120,
child: GestureDetector(
onTap: () async {
await getImageFromGallery();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DisplayPicture(image: galleryImage)));
},
child: Icon(
Icons.image,
color: Colors.white,
size: 60,
)),
),
Positioned(
top: MediaQuery.of(context).size.height - 120,
left: MediaQuery.of(context).size.width / 2.2,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
child: Container(
child: Icon(
Icons.camera,
color: Colors.white,
size: 60,
)),
onTap: () async {
final path = (await getTemporaryDirectory()).path +
'${DateTime.now()}.png';
try {
await _controller.takePicture(path);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DisplayPicture(imagePath: path)));
} catch (e) {
print('EEEE' + e);
}
}))
]));
}
}
class DisplayPicture extends StatelessWidget {
String imagePath;
File image;
String _text;
// File file = File(imagePath)
DisplayPicture({this.imagePath, this.image});
visualImageClassifier(File image) async {
IamOptions options = await IamOptions(
iamApiKey: "NRDjngCby2d-pSHOPyWQJxhuB6vOY2uOTCX6KV2BCfwB",
url:
"https://api.us-south.visual-recognition.watson.cloud.ibm.com/instances/ef286f4e-84c7-44e0-b63d-a6a49a142a30")
.build();
VisualRecognition visualRecognition = new VisualRecognition(
iamOptions: options,
language: Language.ENGLISH); // Language.ENGLISH is language response
ClassifiedImages classifiedImages =
await visualRecognition.classifyImageFile(image.path);
print(classifiedImages
.getImages()[0]
.getClassifiers()[0]
.getClasses()[0]
.className);
// print("${image.toString()}");
// print('ACCESS'+options.accessToken);
//print(options);
//print("${image.path}");
//print('CLASSIFICATION'+classifiedImages.customClasses.toString()); // StreamBuilder(
// stream: StreamMyClassifier(
// image,
// 'NRDjngCby2d-pSHOPyWQJxhuB6vOY2uOTCX6KV2BCfwB', 'CompostxLandfillxRecycle_2056123069'),
// builder: (context, snapshot) {
// if (snapshot.hasData) {
// _text = snapshot.data;
// print(_text);
// }
// else {
// print('NO DATA AVAILABLE');
// }
//
// }
// );
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Center(
child:
image == null ? Image.file(File(imagePath)) : Image.file(image)),
Positioned(
top: MediaQuery.of(context).size.height / 2,
child: FloatingActionButton(
onPressed: () async {
await visualImageClassifier(
image == null ? File(imagePath) : image);
},
child: Icon(Icons.arrow_right)),
)
]));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: VisualPage(),
);
}
}
Error code
E/flutter (25456): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]
Unhandled Exception: NoSuchMethodError: The method '[]' was called on
null. E/flutter (25456): Receiver: null E/flutter (25456): Tried
calling: E/flutter (25456): #0 Object.noSuchMethod
(dart:core-patch/object_patch.dart:53:5) E/flutter (25456): #1
_WeatherState.fetchLocationUpDate. (package:tast_project/screenes/screenweather.dart:31:27) E/flutter
(25456): #2 State.setState
(package:flutter/src/widgets/framework.dart:1148:30) E/flutter
(25456): #3 _WeatherState.fetchLocationUpDate
(package:tast_project/screenes/screenweather.dart:30:5) E/flutter
(25456): E/flutter (25456): #4
_WeatherState.initState (package:tast_project/screenes/screenweather.dart:42:5) E/flutter
(25456): #5 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:4355:58) E/flutter
(25456): #6 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4201:5) E/flutter (25456):
#7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #8 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #9 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:5445:14) E/flutter
(25456): #10 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #11 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #12 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4243:16) E/flutter
(25456): #13 Element.rebuild
(package:flutter/src/widgets/framework.dart:3947:5) E/flutter (25456):
#14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (25456):
#15 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/flutter (25456):
#16 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #17 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #18 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:5445:14) E/flutter
(25456): #19 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #20 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #21 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:5445:14) E/flutter
(25456): #22 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #23 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #24 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4243:16) E/flutter
(25456): #25 Element.rebuild
(package:flutter/src/widgets/framework.dart:3947:5) E/flutter (25456):
#26 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (25456):
#27 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11) E/flutter
(25456): #28 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4201:5) E/flutter (25456):
#29 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #30 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #31 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:5445:14) E/flutter
(25456): #32 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #33 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #34 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:5445:14) E/flutter
(25456): #35 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #36 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #37 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4243:16) E/flutter
(25456): #38 Element.rebuild
(package:flutter/src/widgets/framework.dart:3947:5) E/flutter (25456):
#39 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (25456):
#40 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11) E/flutter
(25456): #41 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4201:5) E/flutter (25456):
#42 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter
(25456): #43 Element.updateChild
(package:flutter/src/widgets/framework.dart:2988:12) E/flutter
(25456): #44 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.da
Flutter code weather
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
const ipkay = '14f4090b86e2548527113ccac56a5ae4';
class _WeatherState extends State<Weather> {
var temp = 0;
String city='';
//var id = 4099194;
String location ;
var textEditingController = TextEditingController();
fetchSearch(String input) async {
http.Response response = await http.get(
"http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=" + input);
var result = json.decode(response.body);
setState(() {
location =result['name'];
});}
fetchLocationUpDate()async{
http.Response response = await http.get(
'http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=$location');
var result = json.decode(response.body);
setState(() {
temp =result['main']['temp'];
city =result['name'];
});}
glo(String city){
fetchSearch(city);
fetchLocationUpDate();}
#override
void initState() {
super.initState();
fetchLocationUpDate();}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Container(
width: size.width,
height: size.height,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assetes/img/night.jpg',
),
fit: BoxFit.fill)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'${temp.toString()} C°',
style: TextStyle(color: Colors.white, fontSize: 30),
),
Text(
'$city',
style: TextStyle(color: Colors.white, fontSize: 30),
),
Card(
child: TextField(
onSubmitted: (String city) {
glo(city);
},
controller: textEditingController,
decoration: InputDecoration(
hintText: 'please entre city',
prefixIcon: Icon(Icons.search),
),
),
),
)
],
),
),
),
);
}
You can copy paste run full code below
Step 1: double temp = 0;
Step 2: glo need async and await
glo(String city) async {
await fetchSearch(city);
await fetchLocationUpDate();
}
Step 3: Check city exist or not
if (result["cod"] == 200) {
setState(() {
location = result['name'];
print("locaton $location");
});
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
const ipkay = '14f4090b86e2548527113ccac56a5ae4';
class _WeatherState extends State<Weather> {
double temp = 0;
//var id = 4099194;
String location;
var textEditingController = TextEditingController();
fetchSearch(String input) async {
http.Response response = await http.get(
"http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=" +
input);
var result = json.decode(response.body);
print("fetchSearch ${response.body}");
if (result["cod"] == 200) {
setState(() {
location = result['name'];
print("locaton $location");
});
}
}
fetchLocationUpDate() async {
print("location to string ${location.toString()}");
http.Response response = await http.get(
'http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=' +
location.toString());
print("LocationUpdate ${response.body}");
var result = json.decode(response.body);
if (result["cod"] == 200) {
setState(() {
temp = result['main']['temp'];
});
}
}
glo(String city) async {
await fetchSearch(city);
await fetchLocationUpDate();
}
#override
void initState() {
super.initState();
//fetchLocationUpDate();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Container(
width: size.width,
height: size.height,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://picsum.photos/250?image=9',
),
fit: BoxFit.fill)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'${temp.toDouble()} C°',
style: TextStyle(color: Colors.white, fontSize: 30),
),
Card(
child: TextField(
onSubmitted: (String city) {
glo(city);
},
controller: textEditingController,
decoration: InputDecoration(
hintText: 'please entre city',
prefixIcon: Icon(Icons.search),
),
),
),
// RaisedButton(
// onPressed: () {
// glo();
// },
// )
],
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Weather(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Every time I log in I get the below error.
I see there is some issue with my Navigator.pushReplacement, which gives error in the console but still allows me to Navigate.
Not sure how to fix this error.
The following code is what I am using. Please let me know if there is any I can get this error fixed.
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen>
with SingleTickerProviderStateMixin {
startTime() async {
var _duration = Duration(seconds: 5);
return Timer(_duration, navigationPage);
}
void navigationPage() {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => FirstTimeUserOnly(),
),
);
}
#override
void initState() {
super.initState();
startTime();
}
final int delayedAmount = 100;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Welcome'),
Logo(),
],
),
),
);
}
}
Here is the error I get
E/flutter (16323): Tried calling: findAncestorStateOfType<NavigatorState>()
E/flutter (16323): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (16323): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:2115:19)
E/flutter (16323): #2 Navigator.pushReplacement (package:flutter/src/widgets/navigator.dart:1781:22)
E/flutter (16323): #3 _WelcomeScreenState.navigationPage (package:/welcome_screen.dart:23:15)
E/flutter (16323): #4 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (16323): #5 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16323): #6 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (16323): #7 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (16323): #8 _rootRun (dart:async/zone.dart:1184:13)
E/flutter (16323): #9 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16323): #10 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1003:23)
E/flutter (16323): #11 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter (16323): #12 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (16323): #13 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (16323): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (16323):
try this, the timer is giving you the error
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen>
with SingleTickerProviderStateMixin {
Timer _timer;
void startTime() async{
_timer = Timer(new Duration(seconds: 5), navigationPage);
}
void navigationPage() {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => FirstTimeUserOnly(),
),
);
}
#override
void initState() {
super.initState();
startTime();
}
#override
void dispose() {
super.dispose();
_timer.cancel();
}
final int delayedAmount = 100;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Welcome'),
Logo(),
],
),
),
);
}
}