Hello I am beginner in the flutter I am build a project which show the some errors which is below
Launching lib\main.dart on M2101K6P in debug mode...
Invalid depfile: D:\Flutter\New\myshop\.dart_tool\flutter_build\47f264e5c74e90bdb7e06ba89ca44716\kernel_snapshot.d
Invalid depfile: D:\Flutter\New\myshop\.dart_tool\flutter_build\47f264e5c74e90bdb7e06ba89ca44716\kernel_snapshot.d
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:dart%3Ahtml; message=StandardFileSystem only supports file:* and data:* URIs)
#0 StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:34:7)
#1 asFileUri (package:vm/kernel_front_end.dart:654:37)
#2 writeDepfile (package:vm/kernel_front_end.dart:794:21)
<asynchronous suspension>
#3 FrontendCompiler.compile (package:frontend_server/frontend_server.dart:629:9)
<asynchronous suspension>
#4 starter (package:frontend_server/starter.dart:99:12)
<asynchronous suspension>
#5 main (file:///C:/b/s/w/ir/x/w/sdk/pkg/frontend_server/bin/frontend_server_starter.dart:13:14)
<asynchronous suspension>
Target kernel_snapshot failed: Exception
FAILURE: Build failed with an exception.
* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1151
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 5s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
And there are my dependencies from the pubsback.yml file
version: 1.0.0+1
environment:
sdk: ">=2.17.6 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
provider: ^6.0.5
intl: ^0.18.0
http: ^0.13.5
shared_preferences: ^2.0.17
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
The error is because of any dependencies version or any other problem form the code, so What the error message tell what's wrong please explain this thing?
This is my main.dart code
import 'package:flutter/material.dart';
import 'package:myshop/screens/splash_screen.dart';
import 'package:provider/provider.dart';
import './screens/products_overview_screen.dart';
import './screens/product_detail_screen.dart';
import './screens/cart_screen.dart';
import './screens/order_screen.dart';
import './screens/user_products_screen.dart';
import './screens/edit_product_screen.dart';
import '../screens/authentication_screen.dart';
import './providers/products.dart';
import './providers/cart.dart';
import './providers/order.dart';
import './providers/auth.dart';
import './providers/auth.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// here new instance of Products is creating so here we have to use the builder methode insted of .value
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (ctx) => Auth()),
ChangeNotifierProxyProvider<Auth, Products>(
create: (_) => Products('', '', []),
update: (ctx, auth, previousProducts) => Products(
auth.token,
auth.userId,
previousProducts == null ? [] : previousProducts.items,
)),
ChangeNotifierProvider(
create: (ctx) => Cart(),
),
ChangeNotifierProxyProvider<Auth, Order>(
create: (ctx) => Order('', '', []),
update: (ctx, auth, order) => Order(
auth.token!,
auth.userId!,
order == null ? [] : order.orders,
),
),
],
child: Consumer<Auth>(builder: (ctx, authData, _) {
return MaterialApp(
title: 'MyShop',
theme: ThemeData(
fontFamily: 'Lato',
colorScheme: ColorScheme.fromSwatch()
.copyWith(primary: Colors.purple, secondary: Colors.deepOrange),
),
home: authData.isAuth
? ProductOverviewScreen()
: FutureBuilder(
builder: (ctx, authSnapShot) =>
authSnapShot.connectionState == ConnectionState.waiting
? SplashScreen()
: AuthenticationScreen()),
routes: {
ProductOverviewScreen.routeName: (context) =>
ProductOverviewScreen(),
AuthenticationScreen.routeName: (context) => AuthenticationScreen(),
ProductDetailScreen.routeName: (context) => ProductDetailScreen(),
CartScreen.routeName: (context) => CartScreen(),
OrderScreen.routeName: (context) => OrderScreen(),
UserProductsScreen.routeName: (context) => UserProductsScreen(),
EditProductScreen.namedRoute: (context) => EditProductScreen(),
},
);
}),
);
}
}
Related
I'm trying to mock go_router in my widget tests but keep getting this error:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No GoRouter found in context
'package:go_router/src/router.dart':
Failed assertion: line 300 pos 12: 'inherited != null'
When the exception was thrown, this was the stack:
#2 GoRouter.of (package:go_router/src/router.dart:300:12)
#3 GoRouterHelper.pushNamed (package:go_router/src/misc/extensions.dart:50:16)
#4 _ProfileEditWidgetState._getSubmitButton.<anonymous closure>.<anonymous closure> (package:app/widgets/profile/profile_edit_widget.dart:236:33)
I'm using go_router 6.0.0
Here's what I have in my test:
final router = MockGoRouter();
when(router.pushNamed(any)).thenReturn(null);
await tester.pumpWidget(
MultiProvider(
providers: [
BlocProvider<ProfileBloc>(create: (context) => profileBloc),
],
child: MaterialApp(
locale: const Locale("en"),
home: InheritedGoRouter(
goRouter: router,
child: ProfileEditWidget(),
),
),
),
);
await tester.pump();
await tester.tap(find.byKey(const Key('btnSubmit')));
await tester.pump();
In my profile edit widget in the submit button on pressed this is what I have:
context.pushNamed(
VERIFY_PHONE,
queryParams: {
'updatedPhone': phone
},
)
There also seems to be no documentation on go to handle testing with go router
Try to change the MaterialApp to MaterialApp.router
And use GoRouter() instead of MockGoRouter()
import 'package:go_router/go_router.dart';
// GoRouter configuration
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
],
);
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}
I get the error
'package:flutter/src/widgets/framework.dart': Failed assertion: line 5356 pos 14: '() {
// check that it really is our d
when I tab on a textview inside my app.
This is how i initialize the app itself.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: Size(460,790),
builder: (context) => MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => TestApp()),
ChangeNotifierProvider(create: (context) => PageControllerProvider()),
ChangeNotifierProvider(create: (context) => RequestProvider()),
ChangeNotifierProvider(create: (context) => HistoryProvider()),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
],
child: App()
),
);
}
}
try updating flutter_screenutil to version 5.5.2 or higher
If you are using the current version of Flutter (v2.10.2>=),
ScreenUtil package creates a conflict with that version.
If you downgrade your Flutter version back to v.2.10.2, the error will be fixed.
You can access it from this link.
Just started working on my app and I'm getting
Bad state: Future already completed
When the exception was thrown, this was the stack:
#1 WidgetsBinding.drawFrame.<anonymous closure> (package:flutter/src/widgets/binding.dart:865:30)
#2 SchedulerBinding._executeTimingsCallbacks (package:flutter/src/scheduler/binding.dart:289:19)
#6 _invoke1 (dart:ui/hooks.dart:182:10)
#7 PlatformDispatcher._reportTimings (dart:ui/platform_dispatcher.dart:441:5)
#8 _reportTimings (dart:ui/hooks.dart:120:31)
...
The TimingsCallback that gets executed was: Closure: (List<FrameTiming>) => void
But There is also
Updated layout information required for RenderParagraph#d3031 NEEDS-LAYOUT NEEDS-PAINT to calculate semantics.
'package:flutter/src/rendering/object.dart':
Failed assertion: line 2653 pos 12: '!_needsLayout'
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
When the exception was thrown, this was the stack:
#2 RenderObject._getSemanticsForParent (package:flutter/src/rendering/object.dart:2653:12)
#3 RenderObject._getSemanticsForParent.<anonymous closure> (package:flutter/src/rendering/object.dart:2675:61)
#4 ContainerRenderObjectMixin.visitChildren (package:flutter/src/rendering/object.dart:3331:14)
#5 RenderObject.visitChildrenForSemantics (package:flutter/src/rendering/object.dart:2760:5)
#6 RenderObject._getSemanticsForParent (package:flutter/src/rendering/object.dart:2670:5)
My code is this so far
Main.dart
void main() => runApp(AppName());
class AppName extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
initialRoute: WelcomeScreen.id,
routes: {
WelcomeScreen.id: (context) => WelcomeScreen(),
SignUpScreen.id: (context) => SignUpScreen(),
LoginScreen.id: (context) => LoginScreen(),
HomeScreen.id: (context) => HomeScreen(),
SearchScreen.id: (context) => SearchScreen(),
MessagesScreen.id: (context) => MessagesScreen(),
ProfileScreen.id: (context) => ProfileScreen(),
RegistraionScreen.id: (context) => RegistraionScreen(),
},
);
}
}
welcome_screen.dart
class WelcomeScreen extends StatefulWidget {
static String id = 'welcome_screen';
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Expanded(
child: Text(
'Welcome',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 40,
color: Colors.white,
),
),
),
);
}
}
I have tried restarting my app restarting my IDE, simulator, and computer to no avail and all the other questions with the same error had something wrong with their flutter however when I run flutter doctor I get no errors
Sorry if it's something small and stupid I'm not seeing I'm new to dart and flutter. Thanks for your help.
I tried removing the Expanded widget in the welcome screen and this solved the issue
I would like to know what is the best way to fetch all the Provider state that I need from an API. I am not doing it on my main screen after login because the initState() always will be called when I navigate back from another screen.
Right now, my approach was creating a LoadScreen widget that is only built after login. There I use FutureBuilder to load the state I need and then Navigate to Main. This approach generates an exception but "works". What would be a correct approach?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shop/providers/auth.dart';
import 'package:shop/providers/collections.dart';
import 'package:shop/providers/customers.dart';
import 'package:shop/providers/orders.dart';
import 'package:shop/providers/products.dart';
import 'package:shop/providers/recommended_categories.dart';
import 'package:shop/providers/user_data.dart';
import 'package:shop/screens/main_screen.dart';
class LoadScreen extends StatelessWidget {
static const routeName = '/load-screen'; //It shouldn't never be used.
#override
Widget build(BuildContext context) {
Future<bool> loadState() async {
//Loading all state data from firebase
print('Loading States');
try {
final authData =
await Provider.of<Auth>(context, listen: false).authData;
final futures = <Future<dynamic>>[
Provider.of<Products>(context, listen: false)
.fetchAndSet(authData), //Products
Provider.of<RecommendedCategories>(context, listen: false)
.fetchAndSet(authData),
Provider.of<Customers>(context, listen: false).fetchAndSet(authData),
Provider.of<Orders>(context, listen: false).fetchAndSet(authData),
Provider.of<UserData>(context, listen: false).fetchAndSet(authData),
Provider.of<Collections>(context, listen: false)
.fetchAndSet(authData),
];
print('Created futures list');
final results = await Future.wait(futures);
print(results);
} catch (error, stacktrace) {
print(error);
print(stacktrace);
throw error;
}
return true;
}
return Scaffold(
body: FutureBuilder(
future: loadState(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
}
Navigator.of(context).pushNamed(MainScreen.routeName);
return Center(
child: Text('Loading...'),
);
} else {
return Center(
child: Text('Loading...'),
);
}
},
),
);
}
}
My main is
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shop/providers/collections.dart';
import 'package:shop/providers/customers.dart';
import 'package:shop/providers/products.dart';
import 'package:shop/providers/recommended_categories.dart';
import 'package:shop/providers/user_data.dart';
import 'package:shop/screens/add_collection_screen.dart';
import 'package:shop/screens/add_order_screen.dart';
import 'package:shop/screens/load_screen.dart';
import 'package:shop/screens/products_screen.dart';
import 'package:shop/screens/customer_order_screen.dart';
import 'package:shop/screens/edit_customer_screen.dart';
import 'package:shop/screens/main_screen.dart';
//import './screens/products_overview_screen.dart';
import 'screens/cart_screen.dart';
import './screens/product_detail_screen.dart';
import './providers/cart.dart';
import './providers/orders.dart';
import './providers/auth.dart';
import './screens/orders_screen.dart';
import './screens/auth_screen.dart';
import './screens/splash-screen.dart';
import './screens/collections_screen.dart';
// import './screens/collection_products_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
print('MyApp.build');
return MultiProvider(
providers: [
ChangeNotifierProvider(
//Recommended approach when a new object is provided.
create: (ctx) => Auth(),
),
ChangeNotifierProvider<Products>(
//Recommended approach when a new object is provided.
create: (ctx) => Products(),
),
ChangeNotifierProvider(
create: (ctx) => Cart(),
),
ChangeNotifierProvider<Orders>(
create: (ctx) => Orders(),
),
ChangeNotifierProvider(
create: (ctx) => Customers(),
),
ChangeNotifierProvider(
create: (ctx) => RecommendedCategories(),
),
ChangeNotifierProvider(
create: (ctx) => UserData(),
),
ChangeNotifierProvider(
create: (ctx) => Collections(),
),
],
child: Consumer<Auth>(
builder: (ctx, auth, _) => MaterialApp(
title: 'Shop',
theme: ThemeData(
primarySwatch: Colors.deepOrange,
accentColor: Colors.purple,
fontFamily: 'Lato',
),
home: auth.canAuth
? LoadScreen()
: FutureBuilder(
future: auth.tryAutoLogin(),
builder: (ctx, authResultSnapshot) =>
authResultSnapshot.connectionState ==
ConnectionState.waiting
? SplashScreen()
: AuthScreen(),
),
routes: {
ProductDetailScreen.routeName: (ctx) => ProductDetailScreen(),
CartScreen.routeName: (ctx) => CartScreen(),
OrdersScreen.routeName: (ctx) => OrdersScreen(),
CollectionProductsScreen.routeName: (ctx) =>
CollectionProductsScreen(),
CollectionsScreen.routeName: (ctx) => CollectionsScreen(false),
EditCustomerScreen.routeName: (ctx) => EditCustomerScreen(),
CustomerOrderScreen.routeName: (ctx) => CustomerOrderScreen(),
AddOrderScreen.routeName: (ctx) => AddOrderScreen(),
AddCollectionScreen.routeName: (ctx) => AddCollectionScreen(),
LoadScreen.routeName: (ctx) => LoadScreen(),
MainScreen.routeName: (ctx) => MainScreen(),
},
),
),
);
}
}
I am getting the following exception
Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building FutureBuilder<bool>(dirty, state: _FutureBuilderState<bool>#547fc):
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>#68f4a]
state: OverlayState#77296(tickers: tracking 0 tickers, entries: [OverlayEntry#847ca(opaque: true; maintainState: false), OverlayEntry#7a334(opaque: false; maintainState: true), OverlayEntry#9e3e0(opaque: false; maintainState: false), OverlayEntry#99d1e(opaque: false; maintainState: true)])
The widget which was currently being built when the offending call was made was: FutureBuilder<bool>
dirty
state: _FutureBuilderState<bool>#547fc
The relevant error-causing widget was
FutureBuilder<bool>
lib/screens/load_screen.dart:48
When the exception was thrown, this was the stack
#0 Element.markNeedsBuild.<anonymous closure>
package:flutter/…/widgets/framework.dart:4138
#1 Element.markNeedsBuild
package:flutter/…/widgets/framework.dart:4153
#2 State.setState
package:flutter/…/widgets/framework.dart:1287
#3 OverlayState.rearrange
package:flutter/…/widgets/overlay.dart:436
#4 NavigatorState._flushHistoryUpdates
package:flutter/…/widgets/navigator.dart:4043
...
════════════════════════════════════════════════════════════════════════════════
E/flutter ( 5098): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2997 pos 18: '!navigator._debugLocked': is not true.
E/flutter ( 5098): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 5098): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter ( 5098): #2 _RouteEntry.handlePush.<anonymous closure>
package:flutter/…/widgets/navigator.dart:2997
E/flutter ( 5098): #3 TickerFuture.whenCompleteOrCancel.thunk
package:flutter/…/scheduler/ticker.dart:407
E/flutter ( 5098): #4 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 5098): #5 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 5098): #6 _FutureListener.handleValue (dart:async/future_impl.dart:152:18)
E/flutter ( 5098): #7 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:704:45)
E/flutter ( 5098): #8 Future._propagateToListeners (dart:async/future_impl.dart:733:32)
E/flutter ( 5098): #9 Future._completeWithValue (dart:async/future_impl.dart:539:5)
E/flutter ( 5098): #10 Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:577:7)
E/flutter ( 5098): #11 _rootRun (dart:async/zone.dart:1354:13)
E/flutter ( 5098): #12 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 5098): #13 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter ( 5098): #14 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter ( 5098): #15 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 5098): #16 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
I suggest you move from futurebuilder to streambuilder then try your provider. I don't like future builder because everytime the widget state changes, the future builder is invoked. The traffic to the server increases. The provider follows the syntax: Provider.of<your_class>(context,listen=false).mymethod. I keep listen=false because I am not doing any broadcast notifications using the provider.
Look at streambuilder and bloc event and data patterns
Everything is working fine with me on iOS and Android but once I run my app on the web (Chrome) I got this error from the widget LocalizedApp
════════ Exception caught by widgets library ═══════════════════════════════════
The following IndexError was thrown building MyApp(dirty):
RangeError (index): Index out of range: no indices are valid: 0
The relevant error-causing widget was
MyApp
lib/main.dart:54
When the exception was thrown, this was the stack
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49 throw_
dart-sdk/lib/_internal/js_dev_runtime/private/js_array.dart 581:7 _get]
packages/localize_and_translate/src/main.dart 192:51 get locale
packages/UnitedPalestine/main.dart 85:28 build
packages/flutter/src/widgets/framework.dart 4569:28 build
...
Any extra steps I need to do to make it works on the web?
Code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
//await Firebase.initializeApp();
// ignore: unused_local_variable
await translator.init(
localeDefault: LocalizationDefaultType.device,
languagesList: <String>['ar', 'en'],
assetsDirectory: 'assets/language/',
apiKeyGoogle: '<Key>',
);
}
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {
//runApp(MyApp());
runApp(
LocalizedApp(
child: MyApp(),
),
);
});
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationService>().authStateChanges,
)
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: SplashScreen.routName,
routes: {
SplashScreen.routName: (ctx) => SplashScreen(),
SigninScreen.routName: (ctx) => SigninScreen(),
SignupScreen.routName: (ctx) => SignupScreen(),
OTPScreen.routName: (ctx) => OTPScreen(),
},
localizationsDelegates: translator.delegates,
locale: translator.locale,
supportedLocales: translator.locals(),
),
);
}
}
That's my main.dart code works perfect on iOS and Android but won't work on the web