Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

flutter - How to load database before init ChangeNotifierProvider?

class MyApp extends StatelessWidget {
  @override
  void initState() {
    onStart();// it is 'Future<void> onStart() async', it will load database from sqlite
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider<HostModel>(create: (context) => HostModel(), lazy: true),
          //this provider depend on onStart() loaded data, so it need to be execute after onStart()
        ],
        child: MaterialApp(
            title: 'Infinite List Sample',
            home: null
        ));
  }
}

MyApp is the first widget in my flutter program. It need to load config data from the sqlite, and then use these data to init provider. But it seem always init the provider before the onStart() function complete, so it cause error.

I have try the futureBuilder, but load data is very quickly (<100ms), so futureBuilder only will produce a 100ms splash screen, it is just a useless flash page.

I also consider the futureProvider, but it seem it can not solve the problem.

I don't know what is a good method to process such problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can call the initial config method in the main function as

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //call the initial config method
  await onStart();
  runApp(MyApp());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...