Index out of range on Flutter Web - flutter

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

Related

The following _CastError was thrown building Builder(dirty):

I'm trying to load my flutter app but I'm getting the error below. I don't know what I'm doing wrong.
EXCEPTION CAUGHT BY WIDGETS LIBRARY the following _CastError was thrown building Builder(dirty): Null check operator used on a null value
here is my code for main.dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
visualDensity: VisualDensity.standard,
),
title: 'lateh',
initialRoute: BuzmeRoutes.profilePage,
routes: BuzmeRoutes.routes,
);
}
}
Your code is working with following way of setting the routes. Please recheck whether you have set the routes in a correct way inside Buzmeroutes.routes:
initialRoute: '/profile',
routes: <String, WidgetBuilder>{
'/profile': (context) => ProfilePage(),
'/login': (context) => LoginPage(),
},

No GoRouter found in context in widget tests

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,
);
}
}

Flutter. Could not find the correct Provider<ThemeChanger> above this Home Widget

I wanted to add theme with provider to my code. I adapted it from this source. https://github.com/lohanidamodar/flutter_theme_provider/blob/master/lib/main.dart .
Even it is same code, I got this error:
"The following ProviderNotFoundException was thrown building Home(dirty, state: _HomeState#c900c):
Error: Could not find the correct Provider above this Home Widget"
This happens because you used a BuildContext that does not include the provider
of your choice.
void main() async {
setPathUrlStrategy();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialAppWithTheme());
}
class MaterialAppWithTheme extends StatefulWidget {
#override
_MaterialAppWithThemeState createState() => _MaterialAppWithThemeState();
}
class _MaterialAppWithThemeState extends State<MaterialAppWithTheme> {
#override
void initState() {
super.initState();
AppRouter appRouter = AppRouter(
routes: AppRoutes.routes,
notFoundHandler: AppRoutes.routeNotFoundHandler,
);
appRouter.setupRoutes();
}
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => ThemeNotifier(),
child: Consumer<ThemeNotifier>(
builder: (context, ThemeNotifier notifier, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: notifier.darkTheme ? dark : light,
onGenerateRoute: AppRouter.router.generator,
);
},
),
);
}
}
Change this:
create: (_) => ThemeNotifier(),
To this:
create: (context) => ThemeNotifier(),

Could not use Provider.of in child widgets

I have my main() like this with MultiProvider wrapped with LocalizedApp for localization:
void main() async {
setupLocator();
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'fa',
supportedLocales: ['fa'],
);
FluroRouter.setupRouter();
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(debug: true);
runApp(
LocalizedApp(
delegate,
MultiProvider(
providers: [
StreamProvider<ConnectionStatus>(
create: (context) =>
ConnectivityService().connectivityController.stream,
initialData: ConnectionStatus.offline,
),
ChangeNotifierProvider<AppState>(
create: (BuildContext context) => AppState(),
),
],
child: MyApp(),
),
),
);
}
and MyApp class is as follows again wrapped with LocalizationProvider:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final appstate = Provider.of<AppState>(context);
var localizationDelegate = LocalizedApp.of(context).delegate;
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: appstate.statusBarColor,
));
return LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
locale: localizationDelegate.currentLocale,
theme: appstate.currentTheme,
initialRoute: 'landing',
onGenerateRoute: FluroRouter.router.generator,
),
),
);
}
}
but even in the initial route which is 'landing' when I try to use a Provider.of<AppState>(context) it throws this error:
Error: Could not find the correct Provider<AppState> above this Landing Widget
This likely happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that Landing is under your MultiProvider/Provider<AppState>.
This usually happen when you are creating a provider and trying to read it immediatly.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builer: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
I don't know what I'm doing wrong here!
also I'm using Fluro v.1.5.1 for navigation.

if the home property is specified the routes table cannot include an entry for /

Getting this error with this code:
void main() => runApp(RouteTestApp());
class RouteTestApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
home: FirstScreen(),
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
);
}
}
The following assertion was thrown building MaterialApp(dirty, state: _MaterialAppState#a959e):
I/flutter (24918): If the home property is specified, the routes table cannot include an entry for "/", since it would
I/flutter (24918): be redundant.
I/flutter (24918): 'package:flutter/src/widgets/app.dart':
I/flutter (24918): Failed assertion: line 172 pos 10: 'home == null ||
I/flutter (24918): !routes.containsKey(Navigator.defaultRouteName)'
The solution is to remove the home property, since it can cause problems if you add the routes property.
class RouteTestApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
);
}
}
If you set none as '/' code bellow will help you when test widgets with navigation, and still work.
final routes = <String, WidgetBuilder>{
'/one': (BuildContext context) => PageOne(),
'/two': (BuildContext context) => PageTwo(),
...
};
runApp(MaterialApp(initialRoute: '/one', routes: appRoutes));