Hi I'm trying to get multiproviders to work in my app where I want to be able to share a set of data across all the child widget. in This case I'm reading file on the filesystem to load a set of data (settings).
FileService.readSettings
static Future<Settings> readSettings() async
{
try {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/settings.txt');
String loadedstring = await file.readAsString();
Settings settings = (jsonDecode(loadedstring) as Settings);
return settings;
} catch (e) {
print("Couldn't read file");
}
}
_getSetting main.dart file
Future<Settings> _getSettings(BuildContext context) async
{
Settings settings = await FileService.readSettings();
return settings;
}
My Build method snippet in main.dart
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => UserData(),
child: MultiProvider(
providers: [
ChangeNotifierProvider<Settings>(
create: (context) => _getSettings(context)
),
],
I haven't composed the create method properly. I'm getting :
Error: A value of type 'Future' can't be assigned to a variable of type 'Settings'.
I'm not sure how to wait for it to load.
You can use FutureBuilder
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _getSettings(context),
builder: (context, snapshot) {
return ChangeNotifierProvider(
create: (context) => UserData(),
child: MultiProvider(
providers: [
ChangeNotifierProvider<Settings>(
create: (context) => snapshot.data
),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.