0

Всем привет. Решил написать первое подобие юзабельного приложения с локальной БД (остановился на Hive). Но проблема в том, что примеры в доках используют main как стартовый экран, хотя это только точка старта. А в реальных приложениях есть ещё SplashScreen. Вобщем, хотелось бы увидеть пример приближенный к боевым. Три файла: **SplashScreen** здесь переход на главный экран происходит по таймингу.

void main() {
  runApp(
    MaterialApp(
      home: MyApp(),
    )
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(
      seconds: 3,
    ), () {
      Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage(),
      ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlutterLogo(
          size: 400,
        ),
      ),
    );
  }
}

**HomePage** пример взят прямо из документации Hive про книги

const favoritesBox = 'favorite_books';
const List<String> books = [
  'Harry Potter',
  'To Kill a Mockingbird',
  'The Hunger Games',
];

void main() async {
  await Hive.initFlutter();
  await Hive.openBox<String>(favoritesBox);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Box<String> favoriteBooksBox;

  @override
  void initState() {
    super.initState();
    favoriteBooksBox = Hive.box(favoritesBox);
  }

  Widget getIcon(int index) {
    if (favoriteBooksBox.containsKey(index)) {
      return Icon(Icons.favorite, color: Colors.red);
    }
    return Icon(Icons.favorite_border);
  }

  void onFavoritePress(int index) {
    if (favoriteBooksBox.containsKey(index)) {
      favoriteBooksBox.delete(index);
      return;
    }
    favoriteBooksBox.put(index, books[index]);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Favorite Books',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Favorite Books'),
        ),
        body: ValueListenableBuilder(
          valueListenable: favoriteBooksBox.listenable(),
          builder: (context, Box<String> box, _) {
            return ListView.builder(
              itemCount: books.length,
              itemBuilder: (context, listIndex) {
                return ListTile(
                  title: Text(books[listIndex]),
                  trailing: IconButton(
                    icon: getIcon(listIndex),
                    onPressed: () => onFavoritePress(listIndex),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

Settings ещё один пример из документации, но пусть это якобы индивидуальные настройки

const darkModeBox = 'darkModeTutorial';

void main() async {
        await Hive.initFlutter();
        await Hive.openBox(darkModeBox);
        runApp(MyApp());
    }

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
        return ValueListenableBuilder(
            valueListenable: Hive.box(darkModeBox).listenable(),
            builder: (context, box, widget) {
            var darkMode = box.get('darkMode', defaultValue: false);
            return MaterialApp(
                themeMode: darkMode ? ThemeMode.dark : ThemeMode.light,
                darkTheme: ThemeData.dark(),
                home: Scaffold(
                        body: Center(
                            child: Switch(
                                value: darkMode,
                                onChanged: (val) {
                                    box.put('darkMode', !darkMode);
                                },
                            ),
                        ),
                ),
            );
        },
        );
    }
}

Как их по уму собрать в кучу? Чтобы SplashScreen убирался не по таймингу, а сначало дожидался подгрузки основного экрана и настроек. Буду признателен за любую помощь.

1 ответ 1

1
@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    Future.wait([
      Hive.initFlutter(),
      Hive.openBox<String>(favoritesBox),
      Hive.openBox(darkModeBox),
      // ...
    ]).then((_) async {
      Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage(),
    });
  });
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.