Reputation: 113
I'm new at flutter, I'm trying here to check if the User Preferences Key exists (Comes from the server API) and in case it does, go to the logged in interface, otherwise go to login.
I'm having a lot of trouble with Future, async and all that stuff, so I'm probably making an stupid mistake, but I can't find it.
Anyways, the error I get is
The following assertion was thrown building FutureBuilder(dirty, state: _FutureBuilderState#5ce9a): setState() or markNeedsBuild() called during build.
Could somebody give me a hand?
Thanks!
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Startup extends StatefulWidget {
const Startup({Key? key}) : super(key: key);
@override
State<Startup> createState() => _StartupState();
}
class _StartupState extends State<Startup> {
Future<String> isLoggedIn() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getString("key") != null) {
return "/MyTasks";
} else {
return "/Login";
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: isLoggedIn(),
builder: (context, snapshot) {
if (snapshot.hasData) {
Navigator.of(context).pushReplacementNamed(snapshot.data.toString());
} else if (snapshot.hasError) {
Text(snapshot.error.toString());
}
return const CircularProgressIndicator();
},
);
}
}
Upvotes: 1
Views: 147
Reputation: 113
I just solved it by adding the async library and surounding my router push command with timer like this:
Timer.run(() {
Navigator.of(context).pushReplacementNamed(snapshot.data.toString());
});
I'll leave it here in case somebody has the same mistake.
Upvotes: 1