LateInitializationError... has not been initialized - flutter

Wondering if anyone can help with the
LateInitializationError: Field'_user#582204964' has not been initialized. when running on the emulator in android studio.
Briefly, I am absolutely new to Flutter and dart. I have been using a tutorial to work along however, unfortunately, a lot of the code has been deprecated and there is no update to the course tutorial. In which case I have been finding the new "methods" and wording to be able to continue with the course and so far so good. However I am stumped at this point with the above error message.
I have put the code that i think is the offending one and hope that someone can point me in the right direction. please take it easy on me as i said I am new and learning to navigate taking baby steps.
thanks in advance.
import 'package:flutter/material.dart';
import 'package:time_tracker/app/sign_in/sign_in_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LandingPage extends StatefulWidget {
#override
_LandingPageState createState() => _LandingPageState();
}
class _LandingPageState extends State<LandingPage> {
late var _user;
void _updateUser (User user){
initUser().whenComplete((){
setState(() {});
});
setState(() {
// _user = user;
});
}
#override
Widget build(BuildContext context) {
if (_user == null){
return SignInPage(
onSignIn: _updateUser,
);
}
return Container(); // Temporary placeholder for homepage
}
}
initUser() {
}

You have comment out the line in which you were initializing the value of user inside the setState((){}) function.

Related

How can I detect share sheet open or closed in flutter programmatically

In my page, there is a share button by using this share package.
Share package
I want, when share sheet comes, the share button become hide, and when share sheet closed, share button wants to be show.. How can I implement this?
Why don't you add this?, Run this command: $ flutter pub add flutter_share
Like what's in here = https://pub.dev/packages/flutter_share/install
instead using share package use flutter_share and use blow code for your purpose.
await FlutterShare.share(title: ' ', text: ' ', linkUrl: your link, chooserTitle: your title).then((value){
//insert your code here for make btn disapeare
print('flutter share now is open') });
You may want to check Share.shareWithResult function which returns ShareResult object. This way you may detect if sheet was dismissed or a successful share took place.
Moreover, you may try WidgetsBindingObserver. When a share sheet is shown the app is in inactive state, when it is closed the app goes into resumed state.
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> with WidgetsBindingObserver {
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print('sheet dismissed');
break;
case AppLifecycleState.inactive:
print('sheet shown');
break;
case AppLifecycleState.paused:
case AppLifecycleState.detached:
break;
}
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
#override
Widget build(BuildContext context) {
return Container();
}
}

setState is not updating the UI even though state is updating

I am trying to wait till amplify configuration is done then load the login screen. Even though state seems to be getting updated I am still getting the loadinscreen. Why is that?
I am not sure if setState is proper method on the init : Importance of Calling SetState inside initState
As per the doc : https://docs.amplify.aws/start/getting-started/integrate/q/integration/flutter/#configure-amplify
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isAmplifyConfigured = false;
late AmplifyAuthCognito auth;
#override
void initState() {
_initializeApp();
super.initState();
}
Future<void> _initializeApp() async {
await _configureAmplify();
setState(() {
_isAmplifyConfigured = true;
});
}
Future<void> _configureAmplify() async {
auth = AmplifyAuthCognito();
try {
await Amplify.addPlugin(auth);
await Amplify.configure(amplifyconfig);
} on AmplifyAlreadyConfiguredException {
print(
'Amplify was already configured. Looks like app restarted on android.');
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateRoute: AppRoutes.onGenerateRoute,
initialRoute: _isAmplifyConfigured
? LoginScreen.routeName
: LoadingScreen.routeName,
);
}
}
I think the issue is with you trying to reassign your initialRoute. I'm not super familiar with this property, but given the name I assume this is set once and is not rebuilt, not even when the state changes. It would make sense, also, because the rest of your code sounds like it should work.
Before trying anything else, I'd recommend you move your logic to initialize Amplify to the LoginScreen, and having its body depend on the _isAmplifyConfigured boolean value. So show spinner if it's false, and show Login fields when it's true.
Even better would be to create a HomeScreen, so you can keep this Amplify initialization at the bottom of your app's stack. And then have your HomeScreen either show the Login widgets, the home screen of your app, or a loading state.

WebSocketChannel becomes null when passed to a StatefulWidget's State class

I have a simple client code in which I'm trying to pass the WebSocketChannel instance to an inner stateful widget, and for some reason when I try to run the code the app crushes and displays on the screen "Unexpected null value. See also: https://flutter.dev/docs/testing/errors". It would be greatly appreciated if someone could explain to me why this happens and how to fix it.
The code:
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class TestWidget extends StatefulWidget {
final WebSocketChannel channel;
const TestWidget(this.channel);
#override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
String buttonText = '';
_TestWidgetState() {
widget.channel.stream.listen((data){
setState(() {buttonText = data;});
});
}
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: (){widget.channel.sink.add('hello');},
child: Text(buttonText)
);
}
}
class App extends StatelessWidget {
final WebSocketChannel channel = WebSocketChannel.connect(
Uri.parse('ws://localhost:8000/')
);
#override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body:
TestWidget(channel)
));
}
}
void main() {
runApp(App());
}
Thanks in advance for the help.
Any particular reason why you put
final WebSocketChannel channel = WebSocketChannel.connect(
Uri.parse('ws://localhost:8000/')
);
in App? Move this line code to TestStateWidget constructor. It's best practice u follow null safety method when try to access an object.

Completer Flutter hook causes bad state error

For managing pull-to-refresh indication in Flutter with BLoC I created a custom Completer hook as an alternative to using a Stateful Widget, and in general, it works fine, however with hot-reload I run into Bad state: Future already completed
import 'dart:async';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class _CompleterHook extends Hook<Completer> {
#override
HookState<Completer, Hook<Completer>> createState() => _CompleterHookState();
}
class _CompleterHookState extends HookState<Completer, _CompleterHook> {
Completer _completer;
#override
void initHook() {
_completer = Completer<void>();
super.initHook();
}
#override
Completer build(BuildContext context) => _completer;
}
Completer<void> useCompleterHook() {
return Hook.use(_CompleterHook());
}
Not sure if there is perhaps something I missed, it's literally only on the HR so completely a development annoyance, I would prefer not to learn to live with it though. Any ideas or suggestions on ways to fix that.
TIA

Transfer variable to other class

I am trying to get a list from class to the other. But I want it to only be transferred after it has got a value assigned from a Future. Is there a way to do so (something like a setState method that acts across classes) My code is here:
class Design extends StatefulWidget {
#override
_DesignState createState() => _DesignState();
}
class _DesignState extends State<Design>{
var Data;
#override
void initState() {
super.initState();
comparer().then((List returnedV){
setState(() {
Data = returnedV;
});
});
}
Future<List> compare() async {
...
return dataDevice
}
}
class AboutSheet extends StatefulWidget {
final List Data;
AboutSheet({#required this.Data});
#override
_AboutSheetState createState() => _AboutSheetState();
}
class _AboutSheetState extends State<AboutSheet> {
}
Every time I use the variable Data in the second class it has the value null. I think it's because I have defined it before with the value null and it's pulling that and is not waiting for the future to assign a value to it. I can't think of a workaround. I would really appreciate your help!
What you are referring to is a state management solution. There is a lot of them, with each their pros and cons. I (and the Flutter team) would suggest Provider.
Take a look at this : List of state management approaches