Last active
March 1, 2020 01:07
-
-
Save tomalabaster/9cef9a50be04f293baa706df67a034e1 to your computer and use it in GitHub Desktop.
BAD: Async init done in a widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class _MyAppState extends State<MyApp> { | |
Database _database; | |
@override | |
void initState() { | |
super.initState(); | |
asyncInitState(); | |
} | |
void asyncInitState() async { | |
var databasesPath = await getDatabasesPath(); | |
var path = join(databasesPath, 'example.db'); | |
setState(() { | |
this._database = await openDatabase(path, version: 1, onCreate: (db, version) async { | |
await db.execute('''CREATE TABLE MyTable ( | |
id INTEGER PRIMARY KEY, | |
name TEXT)'''); | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
... | |
home: this._database == null ? | |
Center(child: CircularProgressIndicator()) : BlocProvider<AppBloc>( | |
create: (context) => MyAppBloc(this._database), | |
child: MasterScreen(), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment