Unimplemented handling of missing static target, Flutter - flutter

I'm writing my Flutter code but I keep getting the error of Unimplemented handling of missing the static target. there is no other error give so I don't know why I'm getting this and there is no way for me to debug it.
The error I'm getting is:
══════ Exception caught by widgets library ═══════════════════════════════════
The following _CompileTimeError was thrown building Wrapper(dirty, dependencies: [InheritedProvider<User>], state: _Wrapper#576d6):
Unimplemented handling of missing static target
The relevant error-causing widget was
Wrapper
lib\main.dart:28
When the exception was thrown, this was the stack
#0 StatefulElement.build
package:flutter/…/widgets/framework.dart:4334
#1 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4223
#2 Element.rebuild
package:flutter/…/widgets/framework.dart:3947
#3 StatefulElement.update
package:flutter/…/widgets/framework.dart:4413
#4 Element.updateChild
package:flutter/…/widgets/framework.dart:2977
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 5 of 544 libraries in 350ms.
════════ Exception caught by widgets library ═══════════════════════════════════
Unimplemented handling of missing static target
The relevant error-causing widget was
Wrapper
My code is :
import 'package:sociagrowapp/models/user.dart';
import 'package:sociagrowapp/HomePages/Home.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sociagrowapp/Authenticate/authenticate.dart';
//import 'package:package_info/package_info.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:sociagrowapp/services/firestore.dart';
import 'package:http/http.dart' as http;
class Wrapper extends StatefulWidget {
#override
createState() => _Wrapper();
}
class _Wrapper extends State<Wrapper> {
#override
Widget build(BuildContext context) {
Future getversionnumber() async {
var data = http.get('https://sociagrow.com/version.html');
print(data);
return data;
}
return FutureBuilder(
future: getversionnumber(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
final user = Provider.of<User>(context);
print(user);
var version = snapshot.data;
// return either the Home or Authenticate widget
if (version == false) {
return Text('Oh no You need to update');
} else {
if (user == null) {
print('Should Changed 3');
return Scaffold(body: Authenticate());
} else {
return PageData();
}
}
} else {
return SpinKitThreeBounce(
color: Colors.blue,
);
}
});
}
}
The strange part is that when I debug it in visual studio code it runs but when I resave and hot reload it I get this error. The problem is not in the http.get() because I got the error with other future functions and firestore as well. really strange though I haven't encountered this type of error and I can't find anything about this error in the internet that could be helpful.

May be hot-reload cache lead to this problem, I just encounter the same problem and I fixed it by stop project then restart it.

You can solve this problem by stopping the debugging or terminate the app.
Then, try to restart or debug the app.

Related

This simple code should produce a white screen in the emulator can't figure out why it's not working

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(),
);
}
}
Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/binding.dart': Failed assertion: line 1220 pos 12: 'renderObject.child == child': is not true.
The relevant error-causing widget was
MaterialApp
lib/main.dart:10
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by scheduler library ═════════════════════════════════
Tried to build dirty widget in the wrong build scope.
I don't really understand but I clicked on start debugging and then it just worked. So I guess that means there's nothing wrong.

The getter 'length' was called on null. fetch from api

I am trying to fetch data from api its splash screen of my app I want user wait 5 second when app is launched and then go to next screen but when I tried fetch data from api I received The getter 'length' was called on null. please help me here is my code I tried resolve it number of other resources but failed to find solution that's why I am posting my question is here please check and help
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_app/main.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(new MaterialApp(
home: new SplashScreen(),
debugShowCheckedModeBanner: false,
routes: <String, WidgetBuilder>{
'/MyHomePage': (BuildContext context) => new MyHomePage()
},
));
}
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => new _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
startTime() async {
var _duration = new Duration(seconds: 5);
return new Timer(_duration, navigationPage);
}
void navigationPage() {
Navigator.of(context).pushReplacementNamed('/MyHomePage');
}
bool _loading=true;
Map data;
List userData=null;
Future getData() async {
http.Response response = await http.get("https://livinghopemobile.com/public/api/fetch-site-settings?token=123ab_#_#AbCD");
data = json.decode(response.body);
debugPrint(response.body);
setState(() {
userData = data["data"];
_loading=false;
// print(userData[0]['title']);
});
}
#override
void initState() {
super.initState();
//startTime();
getData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: ListView.builder(
itemCount:userData.length,
itemBuilder: (context, index) {
return Container(
child: Image.network(userData[index]['site_logo']),
);
}
)
);
}
}
Launching lib/ui/SplashScreen.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done. 23.8s
Debug service listening on ws://127.0.0.1:60469/bL7bmRYyhoc=/ws
Syncing files to device iPhone 11 Pro Max...
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building SplashScreen(dirty, state: _SplashScreenState#5fa75):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was:
SplashScreen file:///Users/apple/livinghopev4/livinghope4ios/lib/ui/SplashScreen.dart:10:15
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _SplashScreenState.build (package:flutter_app/ui/SplashScreen.dart:61:30)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: {"status":200,"message":"Data fetched successfully","data":{"id":1,"site_logo":"https:\/\/livinghopemobile.com\/public\/storage\/site_logo\/270421_122025_image.png","site_name":"Living hope","created_at":null,"updated_at":"2021-04-27T07:20:26.000000Z"}}
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
#0 _SplashScreenState.getData.<anonymous closure> (package:flutter_app/ui/SplashScreen.dart:41:7)
#1 State.setState (package:flutter/src/widgets/framework.dart:1267:30)
#2 _SplashScreenState.getData (package:flutter_app/ui/SplashScreen.dart:40:5)
<asynchronous suspension>
This is because data is not type List, and userData is null hence there is no length to it when you are calling userData.length in ListView.builder.
Change null to [].
{"status":200,"message":"Data fetched successfully","data":{"id":1,"site_logo":"https:\/\/livinghopemobile.com\/public\/storage\/site_logo\/270421_122025_image.png","site_name":"Living hope","created_at":null,"updated_at":"2021-04-27T07:20:26.000000Z"}}
You could append the received data to userData, like: userData.add(data).
You try it:
itemCount:userData.length == null ? 0 : userData.length
Data is returning in Object and you are taking it as List. This is the reason you are getting the error.
Solution:
Don't use Listview.builder as api response is just an object(Map<String, dynamic>).
You can simply use
Image.network(userData['site_logo']),
and everthing will be fine.

"Unhandled Exception: setState() or markNeedsBuild() called during build" when calling Flutter's showDialog()

I encountered with the error described in the title, and later found the culprit, which was a call of showDialog() inside a StreamBuilder.
TL;DR Solution
If calling showDialog()inside StreamBuilder, deleting it might solve the problem.
The code is sampled below:
class SomeClass extends StatefulWidget {
final String restaurantId;
#override
_HomePageState createState() => _HomePageState();
}
class _SomeClassState extends State<SomeClass> {
...
#override
Widget build(BuildContext context) {
...
return StreamBuilder<T>(
stream: _stream,
builder: (context, snapshot) {
// Wait for connection to stablish.
if (snapshot.connectionState == ConnectionState.waiting)
Dialogs.showLoadingDialog(context, _keyLoader);
// Validate there's snapshot data; else, return error.
if (snapshot.hasData) {
... *Build some Scaffold*
} else {
... *Build some Error Message*
}
}
);
}
class Dialogs {
static Future<void> showLoadingDialog(
BuildContext context, GlobalKey key) async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new WillPopScope(
onWillPop: () async => false,
child: Container(
key: key,
child: ...
),
);
},
);
}
}
Why is that, and how can I be able to call showDialog() properly? I found that by deleting the call to showDialog() inside Dialogs.showLoadingDialog() completely solved the problem.
This is the complete error output:
Unhandled Exception: setState() or markNeedsBuild() called during build.
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
Overlay-[LabeledGlobalKey<OverlayState>#c2441]
The widget which was currently being built when the offending call was made was:
StreamBuilder<Restaurant>
#0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4292:11)
#1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4307:6)
#2 State.setState (packag<…>
[VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2416 pos 18: '!navigator._debugLocked': is not true.
...
You need to wait for the widget to build and then call showDialog.
WidgetsBinding.instance.addPostFrameCallback((_) {
// show dialog here
}
I think you need to return a widget from your builder function.
Dialogs.showLoadingDialog(context, _keyLoader);
you need to add 'return' befor this.
Before UI Build we can not call setState. WidgetsBinding.instance.addPostFrameCallback is method which give call back when build is complted.

StreamBuilder<FileSystemEntity>(dirty, state: _StreamBuilderBaseState<FileSystemEntity, AsyncSnapshot<FileSystemEntity>>#25d1b)

I have got an error while working with Stream builders.
In my code, I used if(snapshot.data != null) { list.add(snapshot.data); } but I m getting a msg that add was called on null. I even added print('') statement to check if snapshot.data is null, but it is working fine with print() too. So I m not at all understanding how to solve this error. Someone please respond. Thanks in advance.
Here is my code
class Wrapper extends StatefulWidget {
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
Stream<FileSystemEntity> mystream;
var _directory;
void getfilesdata() async
{
_directory = await getApplicationDocumentsDirectory();
await Directory('${_directory.path}/data').create(recursive: true);
mystream = Directory('${_directory.path}/data').list().map((data) => data);
await Directory('${_directory.path}/documents').create(recursive: true);
}
#override
void initState() {
super.initState();
getfilesdata();
}
#override
Widget build(BuildContext context) {
List<FileSystemEntity> alldata;
return StreamBuilder<FileSystemEntity>(
stream: mystream,
builder: (context, snapshot) {
if(!snapshot.hasData)
{
print('No data yet');
return Loading();
}
else
{
if(snapshot.data != null && !snapshot.hasError)
{
print(snapshot.data);
alldata.add(snapshot.data);
}
if(snapshot.connectionState==ConnectionState.done)
{
return HomeScreen(alldata: alldata);
}
else return Loading();
}
}
);
}
}
And this is the result:
Performing hot restart...
Syncing files to device ZUK Z2132...
Restarted application in 1,734ms.
I/flutter (11840): No data yet
I/flutter (11840): No data yet
I/flutter (11840): File: '/data/user/0/com.example.easyscan/app_flutter/data/data[0]'
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<FileSystemEntity>(dirty, state: _StreamBuilderBaseState<FileSystemEntity, AsyncSnapshot<FileSystemEntity>>#25d1b):
The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of '_File')
The relevant error-causing widget was:
StreamBuilder<FileSystemEntity> file:///home/praneeth/AndroidStudioProjects/easyscan/lib/wrapper.dart:40:12
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _WrapperState.build.<anonymous closure> (package:easyscan/wrapper.dart:53:25)
#2 StreamBuilder.build (package:flutter/src/widgets/async.dart:509:81)
#3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:127:48)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
Your error is because allData is null so you cannot call the add() method.
You can declare your variable as follow:
List<FileSystemEntity> alldata = [];
By doing this allData will be initialized as an empty list and you will be able to call its methods.

Flutter: Can't call Provider<T>.of(context) from a function that is defined into another file. ProviderNotFoundException

I'm new to flutter and I wish to organize my folders in order to write cleaner code.
I'm trying to divide my flutter page on three parts:
login_view.dart (this view will be rendered as the login view and will call functions defined into login_builder.dart to build each of its widgets)
login_builder.dart (contains function definitions called by login_view.dart to build widgets)
login_state.dart (for state management)
But when I call Provider.of(context) inside a functiton that is defined into login_builder.dart (out of the login_view.dart widget tree) it always throws ProviderNotFoundException
// login_view.dart
import 'package:discover/ui/views/login/login_builder.dart';
import 'package:discover/ui/views/login/login_state.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Login extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<LoginState>(
create: (context) => LoginState(),
child: buildLoginForm(context),
);
}
}
// login_builder.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:discover/ui/views/login/login_state.dart';
Widget buildLoginForm(BuildContext context) {
var loginState = Provider.of<LoginState>(context);
return Form(
child: Column(
children: <Widget>[
TextFormField(
onChanged: (value) => loginState.userName = value,
)
],
),
);
}
// login_state.dart
import 'package:flutter/material.dart';
class LoginState extends ChangeNotifier {
String _userName = "";
String get userName => _userName;
set userName(String userName) {
_userName = userName;
}
}
// Debug Console
════════ Exception caught by widgets library ═══════════════════════════════════
The following ProviderNotFoundException was thrown building Login(dirty):
Error: Could not find the correct Provider<LoginState> above this Login Widget
To fix, please:
* Ensure the Provider<LoginState> is an ancestor to this Login Widget
* Provide types to Provider<LoginState>
* Provide types to Consumer<LoginState>
* Provide types to Provider.of<LoginState>()
* Ensure the correct `context` is being used.
If none of these solutions work, please file a bug at:
https://github.com/rrousselGit/provider/issues
The relevant error-causing widget was
Login
When the exception was thrown, this was the stack
Provider.of
buildLoginForm
Login.build
StatelessElement.build
ComponentElement.performRebuild
The context you passed to login_builder is the same context that was passed to login_view, so it exists in a place of the widget tree above where you inserted your ChangeNotifierProvider which is why you can't find it with Provider.of. In order to get this to work the way you want it to, you need to utilize a Builder widget to gain a new BuildContext that exists below the provider:
class Login extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<LoginState>(
create: (context) => LoginState(),
child: Builder(builder: buildLoginForm),
);
}
}
Now the context passed to buildLoginForm will be the context for the Builder (which exists below the provider) instead of for your Login widget (which exists above the provider).