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(),
},
Related
hello I hope you are well, I have the following problem, when I run my app in flutter I get the following ERROR: E/flutter ( 6922): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException( null-error, Host platform returned null value for non-null return value., null, null), as I am working with firebase, but I have searched a lot and the truth is that the solutions that come up have not worked for me or I do not know if it is me who I implemented it incorrectly, soon I will show you the code, thank you very much for stopping to read this publication. I also forgot to mention I'm working on visual studio code
MAIN CODE(),
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'src/Base/Views/BaseView.dart';
import 'src/Feactures/Presentation/Shared/StateProviders/LoadingStateProvider.dart';
import 'src/Feactures/Presentation/Shared/StateProviders/UserStateProvider.dart';
import 'src/Colors/colors.dart';
import 'src/Routes/routes.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:firebase_core/firebase_core.dart';
void main() => runApp(AppState());
class AppState extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => LoadingStateProvider()),
ChangeNotifierProvider(create: (_) => UserStateProvider())
],
child: MyAppUserState(),
);
}
}
class MyAppUserState extends StatelessWidget with BaseView {
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: coordinator.start(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return MyApp(initialRoute: snapshot.data);
} else {
return CircularProgressIndicator();
}
});
}
}
class MyApp extends StatelessWidget {
final String _initialRoute;
MyApp({required String initialRoute}) : _initialRoute = initialRoute;
#override
Widget build(BuildContext context) {
Firebase.initializeApp();
return MaterialApp(
debugShowCheckedModeBanner: false,
routes: routes,
initialRoute: _initialRoute,
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: orange,
appBarTheme:
const AppBarTheme(iconTheme: IconThemeData(color: Colors.black))),
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''), // English, no country code
Locale('es', ''), // Spanish, no country code
],
);
}
}
I really expected the app to run fine but it sends that error
You probably don't want to initialize Firebase in the build method. Try doing this instead (which is in the FlutterFire documentation):
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp();
}
Add the following plugin of the recent/latest version in the pubspec.yaml:
firebase_core :recent version
Please do the following changes in main.dart file.
Hope it works!!
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(AppState());
}
I wonder how to manage screen navigation when your app is connected to Firebase.
When my app was offline I used a routes table, but Im not sure how to do now. Could I do as I show with my code below; use a streambuilder that switches between the AuthScreen when logged out and HomeScreen when logged in, and a routes table to switch with the following screens also when signed in.
I tried this approach but when im signing out from another screen than the HomeScreen the user stays signed in.
How can I set up my routes so that the user always signs out independent from which screen the user's currently on.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterApp',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (
ctx,
userSnapshot,
) {
if (userSnapshot.hasData) {
return HomeScreen();
}
return AuthScreen();
}),
routes: {
Screen1.routeName: (ctx) => Screen1(),
Screen2.routeName: (ctx) => Screen2(),
Screen3.routeName: (ctx) => Screen3(),
Screen4.routeName: (ctx) => Screen4(),
});
}
}
I don't think you're going about this the right way.
They are various ways of doing this. Here's mine.
Firstly, I think you should define an initial route that checks if the user is signed in.
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterApp',
theme: ThemeData(
primarySwatch: Colors.orange,
),
initialRoute:
FirebaseAuth.instance.currentUser == null ? "/login" : "/home",
routes: {
"/home": (ctx) => HomeScreen(),
"/login": (ctx) => AuthScreen(),
Screen1.routeName: (ctx) => Screen1(),
Screen2.routeName: (ctx) => Screen2(),
Screen3.routeName: (ctx) => Screen3(),
Screen4.routeName: (ctx) => Screen4(),
});
}
Note: "/home" & "/login" could be whatever you want as long as it's a string.
For logout, you need to replace the current screen with the login page, something like this should do.
Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
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(),
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
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));