# #firebase #flutter #firebase-authentication #flutter-layout #flutter-test
Вопрос:
Я создаю приложение, пока все работает. Пока я не нажму на кнопку, которая вызывает этот статный виджет:
class ToDo1 extends StatefulWidget {
@override
_ToDo1State createState() => _ToDo1State();
}
class _ToDo1State extends State<ToDo1> {
var User;
late DatabaseService database;
Future<void> connectToFirebase() async{
await Firebase.initializeApp();
final FirebaseAuth auth = FirebaseAuth.instance;
UserCredential result = await FirebaseAuth.instance.signInAnonymously();
User = result.user;
database = DatabaseService(User.uid);
if (!(await database.checkIfUserExists())) {
database.setTodo('To-Do anlegen', false);
}
}
void toggleDone(String key, bool value) {
database.setTodo(key, !value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
'Stufe 1',
style: TextStyle(
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline),
)),
backgroundColor: Color.fromRGBO(35, 112, 192, 1),
),
body: FutureBuilder(
future: connectToFirebase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
return StreamBuilder<DocumentSnapshot> (
stream: database.getTodos(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if(!snapshot.hasData) {
return CircularProgressIndicator();
} else {
Map<String, dynamic> items = snapshot.data!.data as Map<String, dynamic>;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10,
);
},
padding: EdgeInsets.all(10),
itemCount: items.length,
itemBuilder: (BuildContext, i) {
String key = items.keys.elementAt(i);
return ToDoItem(
key,
items[key]!,
() => toggleDone(key, items[key]),
);
});
}
}
);
}
},
)
);
}
}
Затем приложение выходит из строя, и в консоли запуска записывается следующее:
Launching libmain.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built buildappoutputsflutter-apkapp-debug.apk.
Debug service listening on ws://127.0.0.1:50673/exsIqiVEdrE=/ws
Syncing files to device Android SDK built for x86...
W/System (16866): Ignoring header X-Firebase-Locale because its value was null.
W/GooglePlayServicesUtil(16866): Google Play Store is missing.
E/GooglePlayServicesUtil(16866): GooglePlayServices not available due to error 9
W/Firestore(16866): (23.0.3) [GrpcCallProvider]: Failed to update ssl context: com.google.android.gms.common.GooglePlayServicesNotAvailableException
I/TetheringManager(16866): registerTetheringEventCallback:com.example.akne
D/FirebaseAuth(16866): Notifying id token listeners about user ( HT376N4BMNOZgX9VJ9btr6jKpce2 ).
W/om.example.akn(16866): Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (greylist-max-q,core-platform-api, reflection, denied)
W/om.example.akn(16866): Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->getAlpnSelectedProtocol()[B (greylist-max-q, reflection, denied)
E/AndroidRuntime(16866): FATAL EXCEPTION: grpc-okhttp-0
E/AndroidRuntime(16866): Process: com.example.akne, PID: 16866
E/AndroidRuntime(16866): java.lang.AssertionError: Method getAlpnSelectedProtocol not supported for object SSL socket over Socket[address=firestore.googleapis.com/142.250.184.234,port=443,localPort=60722]
E/AndroidRuntime(16866): at io.grpc.okhttp.internal.OptionalMethod.invoke(OptionalMethod.java:114)
E/AndroidRuntime(16866): at io.grpc.okhttp.internal.OptionalMethod.invokeWithoutCheckedException(OptionalMethod.java:135)
E/AndroidRuntime(16866): at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.getSelectedProtocol(OkHttpProtocolNegotiator.java:183)
E/AndroidRuntime(16866): at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.negotiate(OkHttpProtocolNegotiator.java:145)
E/AndroidRuntime(16866): at io.grpc.okhttp.OkHttpTlsUpgrader.upgrade(OkHttpTlsUpgrader.java:63)
E/AndroidRuntime(16866): at io.grpc.okhttp.OkHttpClientTransport$4.run(OkHttpClientTransport.java:571)
E/AndroidRuntime(16866): at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
E/AndroidRuntime(16866): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime(16866): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime(16866): at java.lang.Thread.run(Thread.java:923)
E/libEGL (16866): call to OpenGL ES API with no current context (logged once per thread)
W/System (16866): A resource failed to call close.
W/System (16866): A resource failed to call release.
W/Firestore(16866): (23.0.3) [OnlineStateTracker]: Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds
W/Firestore(16866):
W/Firestore(16866): This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
W/FlutterJNI(16866): Tried to send a platform message response, but FlutterJNI was detached from native C . Could not send. Response ID: 12
W/Firestore(16866): (23.0.3) [WatchStream]: (21e67d7) Stream closed with status: Status{code=UNAVAILABLE, description=Channel shutdownNow invoked, cause=null}.
W/GooglePlayServicesUtil(16866): Google Play Store is missing.
E/GooglePlayServicesUtil(16866): GooglePlayServices not available due to error 9
W/Firestore(16866): (23.0.3) [GrpcCallProvider]: Failed to update ssl context: com.google.android.gms.common.GooglePlayServicesNotAvailableException
W/om.example.akn(16866): Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (greylist-max-q,core-platform-api, reflection, denied)
W/om.example.akn(16866): Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->getAlpnSelectedProtocol()[B (greylist-max-q, reflection, denied)
I/Process (16866): Sending signal. PID: 16866 SIG: 9
Lost connection to device.
This is the class that interacts with the firebase:
class DatabaseService {
final String userID;
DatabaseService(this.userID);
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future setTodo(String item, bool value) async {
return await userTodos.doc(userID).set(
{item:value}, SetOptions(merge: true));
}
Future deleteTodo(String key) async {
return await userTodos.doc(userID).update(
{key: FieldValue.delete(),}
);
}
Future checkIfUserExists() async {
if((await userTodos.doc(userID).get()).exists) {
return true;
}
else {
return false;
}
}
Stream<DocumentSnapshot> getTodos() {
return userTodos.doc(userID).snapshots();
}
}
На случай, если вам это понадобится. Это мой defaultConfig в build.gradle:
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.akne"
minSdkVersion 23
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
Я надеюсь, что предоставил все необходимые данные, чтобы проблема могла быть решена. Если нет, просто напишите мне, и я постараюсь выслать вам необходимый материал.
Комментарии:
1. попробуйте удалить это
await Firebase.initializeApp();
из функцииFuture<void> connectToFirebase()
и добавить вvoid main()
предыдущуюrunApp()
2. Вот так?
void main() async {await Firebase.initializeApp(); runApp(MaterialApp(home: Startseite()));}
Затем он говорит::LateInitializationError: Field 'database' has not been initialized.
3. пожалуйста, поделитесь полным кодом
4. я предполагаю, что предложенные изменения устранят именно ту проблему, с которой вы столкнулись.
5. Я тоже так думаю. Это просто новая ошибка.